David Brown
David Brown

Reputation: 4823

Using utility classes in the android programming

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

Upvotes: 10

Views: 26043

Answers (7)

soumit kolay
soumit kolay

Reputation: 1

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;
}

}

Upvotes: -3

Zar E Ahmer
Zar E Ahmer

Reputation: 34370

  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

Upvotes: 3

Asahi
Asahi

Reputation: 13506

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

Upvotes: 10

kiki
kiki

Reputation: 13997

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();

Upvotes: -2

Cristian
Cristian

Reputation: 200150

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.

Upvotes: 14

skorulis
skorulis

Reputation: 4381

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();

Upvotes: 1

Faisal Abid
Faisal Abid

Reputation: 9140

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()

Upvotes: 0

Related Questions