Using utility classes in the android programming

房东的猫 提交于 2019-12-01 00:38:39

问题


I have a little idea of the Utility Classes with a slight doubt on demand.

If I use a Utility class in my Application than to use that class in my main Activity do I have to create the object of that class or I can directly Import that class in my main activity?

I am Sorry if I am not making a clear sense.

In the nutshell, all I want to be clear about is that basically how can I use the utility class in my Main Activity?

Thanks, david


回答1:


It heavily depends on what kind of utility you're referring to. There are

1) utility classes that implement static methods. In that case you just call them directly using class name

2) utility classes methods that are not static - requires creating and possibly initializing an instance of that class. Then the instance is used to call those methods.

3) utility classes that can be accessed thru Context. then you can call getApplicationContext() and then you can get access to the utility classes




回答2:


It mainly depends on what your utility class does. But, most of the time, if you create an Utility class, you will want to create static methods and invoke them without creating an instance:

class MyUtilities{
    public static String foo(String bar){
        return bar.toUppercase;
    }
}

Then, on your activity:

MyUtilities.foo("baz");

Of course, there are cases where you will want to create instance of a Utility class. For instance, if you have created a global Adapter which will be used by all your ListViews.




回答3:


  public final class Utils
  {
    private Utils() 
    {
    }

    public static void makeToast(Context context, String text){
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }
 }

It's usually a class which only has static methods (possibly with a private constructor and marked abstract/final to prevent instantiation/subclassing). It only exists to make other classes easier to use - for example, providing a bunch of static methods to work with String values, performing extra actions which String itself doesn't support.

Utility classes generally don't operate on classes you have control over, as otherwise you'd usually put the behaviour directly within that class. They're not terribly neat in OO terms, but can still be jolly useful.

as answered by Jon Skeet




回答4:


If the methods in your utility class are static then you can call them from your main activity. eg:

int i = Utility.RandInt();

If they are not static then you have to create an object:

Utility u = new Utility();
int i = u.randInt();



回答5:


If your utility class is created in your Application then you can refer to it by first creating a getMethod in the application class, then going

Application mc = (Application) context.getApplicationContext();

mc.getUtilityClass().SomeMethod()




回答6:


I dont know what yiur exact question is. But here is a code where I used Utility class in my activity. AnimationUtil is used to load animation onto a ImageView.

    ImageView waitImg   = (ImageView) findViewById(R.id.ImageView02);

    Animation waitAnim  = AnimationUtils.loadAnimation(this, R.anim.wait_rotate);

    waitImg.startAnimation(waitAnim); 
    waitAnim.cancel();
    waitAnim.reset();



回答7:


public class Utils {

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

public static void unlockScreenOrientation(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}

public static void lockScreenOrientation(Activity activity) {
    int currentOrientation = activity.getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_PORTRAIT)
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    else
    {
        activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}
// Get Http Post response
@Nullable
public static String getHttpResponse(String url, List<NameValuePair> nameValuePairs) {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    UrlEncodedFormEntity entity;
    try {
        entity = new UrlEncodedFormEntity(nameValuePairs);
        httpPost.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPost);

        HttpEntity resEntity = response.getEntity();
        String res =  EntityUtils.toString(resEntity);
        return res;
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

public static void CopyStream(InputStream is, OutputStream os) {
    final int buffer_size=1024;
    try
    {
        byte[] bytes=new byte[buffer_size];
        for(;;)
        {
            int count=is.read(bytes, 0, buffer_size);
            if(count==-1)
                break;
            os.write(bytes, 0, count);
        }
    }
    catch(Exception ex){}
}

public static JSONObject getJsonObjectFromXmlResponse(String xmlString) {
    JSONObject objectJson = new JSONObject();
    //JSONArray arrayJson = new JSONArray();

    XmlPullParser parser = Xml.newPullParser();
    try {
        parser.setInput(new StringReader(xmlString));
        int eventType = parser.getEventType();

        while (eventType != XmlPullParser.END_DOCUMENT) {
            String name;
            switch (eventType) {
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("string")) {
                        String yourValue = parser.nextText();
                        //arrayJson = new JSONArray(yourValue);
                        objectJson = new JSONObject(yourValue);
                    }
                    break;
            }
            eventType = parser.next();
        }
    } catch (XmlPullParserException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return objectJson;
}

}



来源:https://stackoverflow.com/questions/3930248/using-utility-classes-in-the-android-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!