Question

I am new to Java and I referred regarding my question on the Net but not quite Satisfied. I want to know what the "Utility Class" in Java is?

Can anybody please tell me with an Example.

Thanks, david

Was it helpful?

Solution

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.

OTHER TIPS

To extends Jon Skeet's answer, java.lang.Math, java.util.Collections and java.util.Arrays are typical examples for such classes.

There's a utility package, java.util, that contains a bunch of stuff like dates, times, string tokenizers... Not sure if that's what you're talking about.

Its a class with all static methods and no member elements.

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

}

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top