Android utils classMax heap in JavaSingleton has logic and state, and logic has stateYAuB - Micro Benchmark...

Why does a metal block make a shrill sound but not a wooden block upon hammering?

How to tag distinct options/entities without giving any an implicit priority or suggested order?

What is better: yes / no radio, or simple checkbox?

Why do members of Congress in committee hearings ask witnesses the same question multiple times?

Groups acting on trees

Can I write a book of my D&D game?

Quenching swords in dragon blood; why?

Can a hotel cancel a confirmed reservation?

Is there some relative to Dutch word "kijken" in German?

What is this metal M-shaped device for?

What's a good word to describe a public place that looks like it wouldn't be rough?

Is a debit card dangerous for an account with low balance and no overdraft protection?

Do authors have to be politically correct in article-writing?

How to acknowledge an embarrassing job interview, now that I work directly with the interviewer?

Parsing a string of key-value pairs as a dictionary

Am I a Rude Number?

Why zero tolerance on nudity in space?

A starship is travelling at 0.9c and collides with a small rock. Will it leave a clean hole through, or will more happen?

Can a person refuse a presidential pardon?

How would an AI self awareness kill switch work?

Jumping Numbers

Using only 1s, make 29 with the minimum number of digits

If I sold a PS4 game I owned the disc for, can I reinstall it digitally?

Isn't using the Extrusion Multiplier like cheating?



Android utils class


Max heap in JavaSingleton has logic and state, and logic has stateYAuB - Micro Benchmark Follow-onAndroid SharedPreferencesManager classAndroid manage constant classQuerying Facebook for details of a user's OAuth tokenImplementation of stackTravelling Salesman Problem solverKata calisthenicsReading file from flash with Xamarin.Forms on Android using ActionOpenDocument intent with StartActivityForResult













2












$begingroup$


I have created a Utils class, which consists of progressDialog and AlertDialog:



public class Utils {


public static ProgressDialog dialog;
private static AlertDialog.Builder builder;
private static AlertDialog alert;

public static void showLoader(Activity activity) {
if (dialog == null) {
dialog = new ProgressDialog(activity);
dialog.setMessage(activity.getResources().getString(R.string.loading));
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

}
dialog.show();
}


public static void hideLoader() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}

public static void showOKMessageandBack(String message, final Context activity, final Class activityClass) {
builder = new AlertDialog.Builder(activity);
if (message.length() <= 0)
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.hide();
hideLoader();
Intent intent = new Intent(activity, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
}
});
alert = builder.create();
alert.show();
}


public static void showAlertDialog(final Context context , String title , String message ){

final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// setting Dialog title
alertDialog.setTitle(title);

// setting Dialog message
alertDialog.setMessage(message);

alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});

alertDialog.show();

}
}









share|improve this question











$endgroup$












  • $begingroup$
    You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
    $endgroup$
    – IEatBagels
    Oct 29 '15 at 15:25










  • $begingroup$
    thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
    $endgroup$
    – Mina Fawzy
    Oct 29 '15 at 15:28
















2












$begingroup$


I have created a Utils class, which consists of progressDialog and AlertDialog:



public class Utils {


public static ProgressDialog dialog;
private static AlertDialog.Builder builder;
private static AlertDialog alert;

public static void showLoader(Activity activity) {
if (dialog == null) {
dialog = new ProgressDialog(activity);
dialog.setMessage(activity.getResources().getString(R.string.loading));
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

}
dialog.show();
}


public static void hideLoader() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}

public static void showOKMessageandBack(String message, final Context activity, final Class activityClass) {
builder = new AlertDialog.Builder(activity);
if (message.length() <= 0)
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.hide();
hideLoader();
Intent intent = new Intent(activity, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
}
});
alert = builder.create();
alert.show();
}


public static void showAlertDialog(final Context context , String title , String message ){

final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// setting Dialog title
alertDialog.setTitle(title);

// setting Dialog message
alertDialog.setMessage(message);

alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});

alertDialog.show();

}
}









share|improve this question











$endgroup$












  • $begingroup$
    You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
    $endgroup$
    – IEatBagels
    Oct 29 '15 at 15:25










  • $begingroup$
    thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
    $endgroup$
    – Mina Fawzy
    Oct 29 '15 at 15:28














2












2








2


1



$begingroup$


I have created a Utils class, which consists of progressDialog and AlertDialog:



public class Utils {


public static ProgressDialog dialog;
private static AlertDialog.Builder builder;
private static AlertDialog alert;

public static void showLoader(Activity activity) {
if (dialog == null) {
dialog = new ProgressDialog(activity);
dialog.setMessage(activity.getResources().getString(R.string.loading));
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

}
dialog.show();
}


public static void hideLoader() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}

public static void showOKMessageandBack(String message, final Context activity, final Class activityClass) {
builder = new AlertDialog.Builder(activity);
if (message.length() <= 0)
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.hide();
hideLoader();
Intent intent = new Intent(activity, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
}
});
alert = builder.create();
alert.show();
}


public static void showAlertDialog(final Context context , String title , String message ){

final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// setting Dialog title
alertDialog.setTitle(title);

// setting Dialog message
alertDialog.setMessage(message);

alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});

alertDialog.show();

}
}









share|improve this question











$endgroup$




I have created a Utils class, which consists of progressDialog and AlertDialog:



public class Utils {


public static ProgressDialog dialog;
private static AlertDialog.Builder builder;
private static AlertDialog alert;

public static void showLoader(Activity activity) {
if (dialog == null) {
dialog = new ProgressDialog(activity);
dialog.setMessage(activity.getResources().getString(R.string.loading));
dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);

}
dialog.show();
}


public static void hideLoader() {
if (dialog != null && dialog.isShowing()) {
dialog.dismiss();
dialog = null;
}
}

public static void showOKMessageandBack(String message, final Context activity, final Class activityClass) {
builder = new AlertDialog.Builder(activity);
if (message.length() <= 0)
builder.setMessage(message);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alert.hide();
hideLoader();
Intent intent = new Intent(activity, activityClass);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivity(intent);
}
});
alert = builder.create();
alert.show();
}


public static void showAlertDialog(final Context context , String title , String message ){

final AlertDialog alertDialog = new AlertDialog.Builder(context).create();

// setting Dialog title
alertDialog.setTitle(title);

// setting Dialog message
alertDialog.setMessage(message);

alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});

alertDialog.show();

}
}






java android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 3 '15 at 18:48









Jamal

30.3k11119227




30.3k11119227










asked Oct 29 '15 at 11:44









Mina FawzyMina Fawzy

2902521




2902521












  • $begingroup$
    You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
    $endgroup$
    – IEatBagels
    Oct 29 '15 at 15:25










  • $begingroup$
    thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
    $endgroup$
    – Mina Fawzy
    Oct 29 '15 at 15:28


















  • $begingroup$
    You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
    $endgroup$
    – IEatBagels
    Oct 29 '15 at 15:25










  • $begingroup$
    thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
    $endgroup$
    – Mina Fawzy
    Oct 29 '15 at 15:28
















$begingroup$
You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
$endgroup$
– IEatBagels
Oct 29 '15 at 15:25




$begingroup$
You cannot ask us to add code to your class, though we can review it :) I edited that part out of your question and corrected some of the spelling mistakes it had.
$endgroup$
– IEatBagels
Oct 29 '15 at 15:25












$begingroup$
thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
$endgroup$
– Mina Fawzy
Oct 29 '15 at 15:28




$begingroup$
thank you for advice , I edit my question , I need review this class , is their any way to make looks code better
$endgroup$
– Mina Fawzy
Oct 29 '15 at 15:28










3 Answers
3






active

oldest

votes


















7












$begingroup$

I'm looking at this class and I'm confused.

The reason why is that I'm doing web programming so a dialog can be asked on different sessions.

In that case this class is useless.



In stead of holding your ProgressDialog and AlertDialog in your class as static variable, just return them in the method.

Then your



public static void hideLoader()


should be changed to :



public static void hideLoader(ProgressDialog dialog)


So with a small refactoring you create a class what could be good for multiple users application.

Other advantage is you can call the method multiple times, where in your setup this was impossible and even dangereous.



Naming your class :



A class Utils is just so poor chosen.

If you see a class name like that, what do you expect what's in it?

It could be Utils for Strings like StringUtils or more like MathUtils?

As you see at this name, you already know what to expect from it.

A better name could be DialogUtil



Constants :



In android there is a class R.string who have a lot of constants.

In stead of doing this :



builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


You could do :



builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {


It's cleaner code who saves a little amount of memory because you don't need to recreate the String every time you call the method.






share|improve this answer









$endgroup$





















    4












    $begingroup$

    Static variables



    The variables builder and alert should not be static, as they are only used in one function and do not persist.



    The one place you use alert past the end of the function is in the callback function. But you shouldn't be using it there:




               alert.hide();



    should be:



                dialog.hide();





    share|improve this answer









    $endgroup$





















      0












      $begingroup$

      imports



       import android.annotation.SuppressLint;
      import android.app.Activity;
      import android.app.AlertDialog;
      import android.content.Context;
      import android.content.DialogInterface;
      import android.content.Intent;
      import android.content.res.Resources;
      import android.location.LocationManager;
      import android.net.ConnectivityManager;
      import android.net.NetworkInfo;
      import android.net.Uri;
      import android.os.Build;
      import android.os.Environment;
      import android.provider.MediaStore;
      import android.util.Log;
      import android.util.TypedValue;
      import android.view.View;
      import android.view.ViewGroup;
      import android.view.inputmethod.InputMethodManager;
      import android.widget.EditText;

      import java.io.BufferedReader;
      import java.io.File;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.net.HttpURLConnection;
      import java.net.URL;
      import java.text.SimpleDateFormat;
      import java.util.Date;
      import java.util.TimeZone;
      import java.util.concurrent.TimeUnit;
      import java.util.regex.Matcher;
      import java.util.regex.Pattern;


      class is here



      public class Utils {
      /**
      * Convertim to time format
      *
      * @param unix is time with long value
      * @return string time
      */
      public static String convertUnix2Date(long unix) {
      if (unix == 0) return "";
      String result;
      Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
      @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
      f.setTimeZone(TimeZone.getDefault());
      result = f.format(date);
      return result;
      }

      /**
      * Handling the keyboard on device
      *
      * @param activity
      */
      private static void hideSoftKeyboard(Activity activity) {
      InputMethodManager inputMethodManager =
      (InputMethodManager) activity.getSystemService(
      Activity.INPUT_METHOD_SERVICE);
      if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
      inputMethodManager.hideSoftInputFromWindow(
      activity.getCurrentFocus().getWindowToken(), 0);
      }
      }

      /**
      * Handling the listener to dismiss the keyboard on device
      *
      * @param context <br>
      * @param view is parent view <br>
      */
      public static void setupDismissKeyboardListener(Context context, View view) {

      // Set up touch listener for non-text box views to hide keyboard.
      if (!(view instanceof EditText)) {
      view.setOnTouchListener((v, event) -> {
      hideSoftKeyboard((Activity) context);
      return false;
      });
      }

      //If a layout container, iterate over children and seed recursion.
      if (view instanceof ViewGroup) {
      for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
      View innerView = ((ViewGroup) view).getChildAt(i);
      setupDismissKeyboardListener(context, innerView);
      }
      }
      }


      /**
      * Converting the DP value to PX to display on device
      *
      * @param context <br>
      * @param value is DP value
      * @return PX value
      */
      public static int parseFromDPtoPX(Context context, float value) {
      Resources resources = context.getResources();
      return (int) TypedValue.applyDimension(
      TypedValue.COMPLEX_UNIT_DIP,
      value,
      resources.getDisplayMetrics()
      );
      }


      public static void setupUI(View view, final Activity activity) {
      //Set up touch listener for non-text box views to hide keyboard.
      if(!(view instanceof EditText)) {
      view.setOnTouchListener((v, event) -> {
      hideSoftKeyboard(activity);
      return false;
      });
      }

      //If a layout container, iterate over children and seed recursion.
      if (view instanceof ViewGroup) {
      for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
      View innerView = ((ViewGroup) view).getChildAt(i);
      setupUI(innerView, activity);
      }
      }
      }


      /**
      *
      */
      protected Utils() {

      }

      public static final String TAG = "Utils";
      public static final int DEFAULT_BUFFER_SIZE = 8192;
      private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$";

      /**
      * @return true if JellyBean or higher
      */
      public static boolean isJellyBeanOrHigher() {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
      }

      /**
      * @return true if Ice Cream or higher
      */
      public static boolean isICSOrHigher() {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
      }

      /**
      * @return true if HoneyComb or higher
      */
      public static boolean isHoneycombOrHigher() {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
      }

      /**
      * @return true if GingerBreak or higher
      */
      public static boolean isGingerbreadOrHigher() {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
      }

      /**
      * @return true if Froyo or higher
      */
      public static boolean isFroyoOrHigher() {
      return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
      }

      /**
      * Check SdCard
      *
      * @return true if External Strorage available
      */
      public static boolean isExtStorageAvailable() {
      return Environment.MEDIA_MOUNTED.equals(Environment
      .getExternalStorageState());
      }

      /**
      * Check internet
      *
      * @param context
      * @return true if Network connected
      */
      public static boolean isNetworkConnected(Context context) {
      ConnectivityManager connectivityManager = (ConnectivityManager) context
      .getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo activeNetworkInfo = connectivityManager
      .getActiveNetworkInfo();
      if (activeNetworkInfo != null) {
      return activeNetworkInfo.isConnected();
      }
      return false;
      }

      /**
      * Check wifi
      *
      * @param context
      * @return true if Wifi connected
      */
      public static boolean isWifiConnected(Context context) {
      ConnectivityManager connectivityManager = (ConnectivityManager) context
      .getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo wifiNetworkInfo = connectivityManager
      .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
      if (wifiNetworkInfo != null) {
      return wifiNetworkInfo.isConnected();
      }
      return false;
      }

      /**
      * Check on/off gps
      *
      * @return true if GPS available
      */
      public static boolean checkAvailableGps(Context context) {
      LocationManager manager = (LocationManager) context
      .getSystemService(Context.LOCATION_SERVICE);

      return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
      }

      /**
      * Download data url
      *
      * @param urlString
      * @return InputStream
      * @throws IOException IOException
      */


      /**
      * @return an {@link HttpURLConnection} using sensible default settings for
      * mobile and taking care of buggy behavior prior to Froyo.
      * @throws IOException exception
      */
      public static HttpURLConnection buildHttpUrlConnection(String urlString)
      throws IOException {
      Utils.disableConnectionReuseIfNecessary();

      URL url = new URL(urlString);

      HttpURLConnection conn = (HttpURLConnection) url.openConnection();
      conn.setReadTimeout(10000 /* milliseconds */);
      conn.setConnectTimeout(15000 /* milliseconds */);
      conn.setDoInput(true);
      conn.setRequestMethod("GET");
      return conn;
      }

      /**
      * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
      * frustrating bugs. In particular, calling close() on a readable
      * InputStream could poison the connection pool. Work around this by
      * disabling connection pooling.
      */
      public static void disableConnectionReuseIfNecessary() {
      // HTTP connection reuse which was buggy pre-froyo
      if (!isFroyoOrHigher()) {
      System.setProperty("http.keepAlive", "false");
      }
      }

      /**
      * Check an email is valid or not
      *
      * @param email the email need to check
      * @return {@code true} if valid, {@code false} if invalid
      */
      public static boolean isValidEmail(Context context, String email) {
      boolean result = false;
      Pattern pt = Pattern.compile(sFormatEmail);
      Matcher mt = pt.matcher(email);
      if (mt.matches()) {
      result = true;
      }
      return result;
      }

      /**
      * A method to download json data from url
      */
      @SuppressWarnings("ThrowFromFinallyBlock")
      public static String downloadUrl(String strUrl) throws IOException {
      String data = "";
      InputStream iStream = null;
      HttpURLConnection urlConnection = null;
      try {
      URL url = new URL(strUrl);

      // Creating an http connection to communicate with url
      urlConnection = (HttpURLConnection) url.openConnection();

      // Connecting to url
      urlConnection.connect();

      // Reading data from url
      iStream = urlConnection.getInputStream();

      BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

      StringBuilder sb = new StringBuilder();

      String line;
      while ((line = br.readLine()) != null) {
      sb.append(line);
      }

      data = sb.toString();

      br.close();

      } catch (Exception e) {
      Log.d("Exception", e.toString());
      } finally {
      assert iStream != null;
      iStream.close();
      urlConnection.disconnect();
      }
      return data;
      }


      }



      hope will be helpful





      share








      New contributor




      Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      $endgroup$













        Your Answer





        StackExchange.ifUsing("editor", function () {
        return StackExchange.using("mathjaxEditing", function () {
        StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
        StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
        });
        });
        }, "mathjax-editing");

        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "196"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: false,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: null,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f109105%2fandroid-utils-class%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        3 Answers
        3






        active

        oldest

        votes








        3 Answers
        3






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        7












        $begingroup$

        I'm looking at this class and I'm confused.

        The reason why is that I'm doing web programming so a dialog can be asked on different sessions.

        In that case this class is useless.



        In stead of holding your ProgressDialog and AlertDialog in your class as static variable, just return them in the method.

        Then your



        public static void hideLoader()


        should be changed to :



        public static void hideLoader(ProgressDialog dialog)


        So with a small refactoring you create a class what could be good for multiple users application.

        Other advantage is you can call the method multiple times, where in your setup this was impossible and even dangereous.



        Naming your class :



        A class Utils is just so poor chosen.

        If you see a class name like that, what do you expect what's in it?

        It could be Utils for Strings like StringUtils or more like MathUtils?

        As you see at this name, you already know what to expect from it.

        A better name could be DialogUtil



        Constants :



        In android there is a class R.string who have a lot of constants.

        In stead of doing this :



        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


        You could do :



        builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {


        It's cleaner code who saves a little amount of memory because you don't need to recreate the String every time you call the method.






        share|improve this answer









        $endgroup$


















          7












          $begingroup$

          I'm looking at this class and I'm confused.

          The reason why is that I'm doing web programming so a dialog can be asked on different sessions.

          In that case this class is useless.



          In stead of holding your ProgressDialog and AlertDialog in your class as static variable, just return them in the method.

          Then your



          public static void hideLoader()


          should be changed to :



          public static void hideLoader(ProgressDialog dialog)


          So with a small refactoring you create a class what could be good for multiple users application.

          Other advantage is you can call the method multiple times, where in your setup this was impossible and even dangereous.



          Naming your class :



          A class Utils is just so poor chosen.

          If you see a class name like that, what do you expect what's in it?

          It could be Utils for Strings like StringUtils or more like MathUtils?

          As you see at this name, you already know what to expect from it.

          A better name could be DialogUtil



          Constants :



          In android there is a class R.string who have a lot of constants.

          In stead of doing this :



          builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


          You could do :



          builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {


          It's cleaner code who saves a little amount of memory because you don't need to recreate the String every time you call the method.






          share|improve this answer









          $endgroup$
















            7












            7








            7





            $begingroup$

            I'm looking at this class and I'm confused.

            The reason why is that I'm doing web programming so a dialog can be asked on different sessions.

            In that case this class is useless.



            In stead of holding your ProgressDialog and AlertDialog in your class as static variable, just return them in the method.

            Then your



            public static void hideLoader()


            should be changed to :



            public static void hideLoader(ProgressDialog dialog)


            So with a small refactoring you create a class what could be good for multiple users application.

            Other advantage is you can call the method multiple times, where in your setup this was impossible and even dangereous.



            Naming your class :



            A class Utils is just so poor chosen.

            If you see a class name like that, what do you expect what's in it?

            It could be Utils for Strings like StringUtils or more like MathUtils?

            As you see at this name, you already know what to expect from it.

            A better name could be DialogUtil



            Constants :



            In android there is a class R.string who have a lot of constants.

            In stead of doing this :



            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


            You could do :



            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {


            It's cleaner code who saves a little amount of memory because you don't need to recreate the String every time you call the method.






            share|improve this answer









            $endgroup$



            I'm looking at this class and I'm confused.

            The reason why is that I'm doing web programming so a dialog can be asked on different sessions.

            In that case this class is useless.



            In stead of holding your ProgressDialog and AlertDialog in your class as static variable, just return them in the method.

            Then your



            public static void hideLoader()


            should be changed to :



            public static void hideLoader(ProgressDialog dialog)


            So with a small refactoring you create a class what could be good for multiple users application.

            Other advantage is you can call the method multiple times, where in your setup this was impossible and even dangereous.



            Naming your class :



            A class Utils is just so poor chosen.

            If you see a class name like that, what do you expect what's in it?

            It could be Utils for Strings like StringUtils or more like MathUtils?

            As you see at this name, you already know what to expect from it.

            A better name could be DialogUtil



            Constants :



            In android there is a class R.string who have a lot of constants.

            In stead of doing this :



            builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {


            You could do :



            builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {


            It's cleaner code who saves a little amount of memory because you don't need to recreate the String every time you call the method.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 3 '15 at 7:37









            chillworldchillworld

            3,53611547




            3,53611547

























                4












                $begingroup$

                Static variables



                The variables builder and alert should not be static, as they are only used in one function and do not persist.



                The one place you use alert past the end of the function is in the callback function. But you shouldn't be using it there:




                           alert.hide();



                should be:



                            dialog.hide();





                share|improve this answer









                $endgroup$


















                  4












                  $begingroup$

                  Static variables



                  The variables builder and alert should not be static, as they are only used in one function and do not persist.



                  The one place you use alert past the end of the function is in the callback function. But you shouldn't be using it there:




                             alert.hide();



                  should be:



                              dialog.hide();





                  share|improve this answer









                  $endgroup$
















                    4












                    4








                    4





                    $begingroup$

                    Static variables



                    The variables builder and alert should not be static, as they are only used in one function and do not persist.



                    The one place you use alert past the end of the function is in the callback function. But you shouldn't be using it there:




                               alert.hide();



                    should be:



                                dialog.hide();





                    share|improve this answer









                    $endgroup$



                    Static variables



                    The variables builder and alert should not be static, as they are only used in one function and do not persist.



                    The one place you use alert past the end of the function is in the callback function. But you shouldn't be using it there:




                               alert.hide();



                    should be:



                                dialog.hide();






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 3 '15 at 9:29









                    JS1JS1

                    27.4k32976




                    27.4k32976























                        0












                        $begingroup$

                        imports



                         import android.annotation.SuppressLint;
                        import android.app.Activity;
                        import android.app.AlertDialog;
                        import android.content.Context;
                        import android.content.DialogInterface;
                        import android.content.Intent;
                        import android.content.res.Resources;
                        import android.location.LocationManager;
                        import android.net.ConnectivityManager;
                        import android.net.NetworkInfo;
                        import android.net.Uri;
                        import android.os.Build;
                        import android.os.Environment;
                        import android.provider.MediaStore;
                        import android.util.Log;
                        import android.util.TypedValue;
                        import android.view.View;
                        import android.view.ViewGroup;
                        import android.view.inputmethod.InputMethodManager;
                        import android.widget.EditText;

                        import java.io.BufferedReader;
                        import java.io.File;
                        import java.io.IOException;
                        import java.io.InputStream;
                        import java.io.InputStreamReader;
                        import java.net.HttpURLConnection;
                        import java.net.URL;
                        import java.text.SimpleDateFormat;
                        import java.util.Date;
                        import java.util.TimeZone;
                        import java.util.concurrent.TimeUnit;
                        import java.util.regex.Matcher;
                        import java.util.regex.Pattern;


                        class is here



                        public class Utils {
                        /**
                        * Convertim to time format
                        *
                        * @param unix is time with long value
                        * @return string time
                        */
                        public static String convertUnix2Date(long unix) {
                        if (unix == 0) return "";
                        String result;
                        Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
                        @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
                        f.setTimeZone(TimeZone.getDefault());
                        result = f.format(date);
                        return result;
                        }

                        /**
                        * Handling the keyboard on device
                        *
                        * @param activity
                        */
                        private static void hideSoftKeyboard(Activity activity) {
                        InputMethodManager inputMethodManager =
                        (InputMethodManager) activity.getSystemService(
                        Activity.INPUT_METHOD_SERVICE);
                        if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
                        inputMethodManager.hideSoftInputFromWindow(
                        activity.getCurrentFocus().getWindowToken(), 0);
                        }
                        }

                        /**
                        * Handling the listener to dismiss the keyboard on device
                        *
                        * @param context <br>
                        * @param view is parent view <br>
                        */
                        public static void setupDismissKeyboardListener(Context context, View view) {

                        // Set up touch listener for non-text box views to hide keyboard.
                        if (!(view instanceof EditText)) {
                        view.setOnTouchListener((v, event) -> {
                        hideSoftKeyboard((Activity) context);
                        return false;
                        });
                        }

                        //If a layout container, iterate over children and seed recursion.
                        if (view instanceof ViewGroup) {
                        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                        View innerView = ((ViewGroup) view).getChildAt(i);
                        setupDismissKeyboardListener(context, innerView);
                        }
                        }
                        }


                        /**
                        * Converting the DP value to PX to display on device
                        *
                        * @param context <br>
                        * @param value is DP value
                        * @return PX value
                        */
                        public static int parseFromDPtoPX(Context context, float value) {
                        Resources resources = context.getResources();
                        return (int) TypedValue.applyDimension(
                        TypedValue.COMPLEX_UNIT_DIP,
                        value,
                        resources.getDisplayMetrics()
                        );
                        }


                        public static void setupUI(View view, final Activity activity) {
                        //Set up touch listener for non-text box views to hide keyboard.
                        if(!(view instanceof EditText)) {
                        view.setOnTouchListener((v, event) -> {
                        hideSoftKeyboard(activity);
                        return false;
                        });
                        }

                        //If a layout container, iterate over children and seed recursion.
                        if (view instanceof ViewGroup) {
                        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                        View innerView = ((ViewGroup) view).getChildAt(i);
                        setupUI(innerView, activity);
                        }
                        }
                        }


                        /**
                        *
                        */
                        protected Utils() {

                        }

                        public static final String TAG = "Utils";
                        public static final int DEFAULT_BUFFER_SIZE = 8192;
                        private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$";

                        /**
                        * @return true if JellyBean or higher
                        */
                        public static boolean isJellyBeanOrHigher() {
                        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
                        }

                        /**
                        * @return true if Ice Cream or higher
                        */
                        public static boolean isICSOrHigher() {
                        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
                        }

                        /**
                        * @return true if HoneyComb or higher
                        */
                        public static boolean isHoneycombOrHigher() {
                        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
                        }

                        /**
                        * @return true if GingerBreak or higher
                        */
                        public static boolean isGingerbreadOrHigher() {
                        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
                        }

                        /**
                        * @return true if Froyo or higher
                        */
                        public static boolean isFroyoOrHigher() {
                        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
                        }

                        /**
                        * Check SdCard
                        *
                        * @return true if External Strorage available
                        */
                        public static boolean isExtStorageAvailable() {
                        return Environment.MEDIA_MOUNTED.equals(Environment
                        .getExternalStorageState());
                        }

                        /**
                        * Check internet
                        *
                        * @param context
                        * @return true if Network connected
                        */
                        public static boolean isNetworkConnected(Context context) {
                        ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo activeNetworkInfo = connectivityManager
                        .getActiveNetworkInfo();
                        if (activeNetworkInfo != null) {
                        return activeNetworkInfo.isConnected();
                        }
                        return false;
                        }

                        /**
                        * Check wifi
                        *
                        * @param context
                        * @return true if Wifi connected
                        */
                        public static boolean isWifiConnected(Context context) {
                        ConnectivityManager connectivityManager = (ConnectivityManager) context
                        .getSystemService(Context.CONNECTIVITY_SERVICE);
                        NetworkInfo wifiNetworkInfo = connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        if (wifiNetworkInfo != null) {
                        return wifiNetworkInfo.isConnected();
                        }
                        return false;
                        }

                        /**
                        * Check on/off gps
                        *
                        * @return true if GPS available
                        */
                        public static boolean checkAvailableGps(Context context) {
                        LocationManager manager = (LocationManager) context
                        .getSystemService(Context.LOCATION_SERVICE);

                        return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                        }

                        /**
                        * Download data url
                        *
                        * @param urlString
                        * @return InputStream
                        * @throws IOException IOException
                        */


                        /**
                        * @return an {@link HttpURLConnection} using sensible default settings for
                        * mobile and taking care of buggy behavior prior to Froyo.
                        * @throws IOException exception
                        */
                        public static HttpURLConnection buildHttpUrlConnection(String urlString)
                        throws IOException {
                        Utils.disableConnectionReuseIfNecessary();

                        URL url = new URL(urlString);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        conn.setReadTimeout(10000 /* milliseconds */);
                        conn.setConnectTimeout(15000 /* milliseconds */);
                        conn.setDoInput(true);
                        conn.setRequestMethod("GET");
                        return conn;
                        }

                        /**
                        * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
                        * frustrating bugs. In particular, calling close() on a readable
                        * InputStream could poison the connection pool. Work around this by
                        * disabling connection pooling.
                        */
                        public static void disableConnectionReuseIfNecessary() {
                        // HTTP connection reuse which was buggy pre-froyo
                        if (!isFroyoOrHigher()) {
                        System.setProperty("http.keepAlive", "false");
                        }
                        }

                        /**
                        * Check an email is valid or not
                        *
                        * @param email the email need to check
                        * @return {@code true} if valid, {@code false} if invalid
                        */
                        public static boolean isValidEmail(Context context, String email) {
                        boolean result = false;
                        Pattern pt = Pattern.compile(sFormatEmail);
                        Matcher mt = pt.matcher(email);
                        if (mt.matches()) {
                        result = true;
                        }
                        return result;
                        }

                        /**
                        * A method to download json data from url
                        */
                        @SuppressWarnings("ThrowFromFinallyBlock")
                        public static String downloadUrl(String strUrl) throws IOException {
                        String data = "";
                        InputStream iStream = null;
                        HttpURLConnection urlConnection = null;
                        try {
                        URL url = new URL(strUrl);

                        // Creating an http connection to communicate with url
                        urlConnection = (HttpURLConnection) url.openConnection();

                        // Connecting to url
                        urlConnection.connect();

                        // Reading data from url
                        iStream = urlConnection.getInputStream();

                        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                        StringBuilder sb = new StringBuilder();

                        String line;
                        while ((line = br.readLine()) != null) {
                        sb.append(line);
                        }

                        data = sb.toString();

                        br.close();

                        } catch (Exception e) {
                        Log.d("Exception", e.toString());
                        } finally {
                        assert iStream != null;
                        iStream.close();
                        urlConnection.disconnect();
                        }
                        return data;
                        }


                        }



                        hope will be helpful





                        share








                        New contributor




                        Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                        Check out our Code of Conduct.






                        $endgroup$


















                          0












                          $begingroup$

                          imports



                           import android.annotation.SuppressLint;
                          import android.app.Activity;
                          import android.app.AlertDialog;
                          import android.content.Context;
                          import android.content.DialogInterface;
                          import android.content.Intent;
                          import android.content.res.Resources;
                          import android.location.LocationManager;
                          import android.net.ConnectivityManager;
                          import android.net.NetworkInfo;
                          import android.net.Uri;
                          import android.os.Build;
                          import android.os.Environment;
                          import android.provider.MediaStore;
                          import android.util.Log;
                          import android.util.TypedValue;
                          import android.view.View;
                          import android.view.ViewGroup;
                          import android.view.inputmethod.InputMethodManager;
                          import android.widget.EditText;

                          import java.io.BufferedReader;
                          import java.io.File;
                          import java.io.IOException;
                          import java.io.InputStream;
                          import java.io.InputStreamReader;
                          import java.net.HttpURLConnection;
                          import java.net.URL;
                          import java.text.SimpleDateFormat;
                          import java.util.Date;
                          import java.util.TimeZone;
                          import java.util.concurrent.TimeUnit;
                          import java.util.regex.Matcher;
                          import java.util.regex.Pattern;


                          class is here



                          public class Utils {
                          /**
                          * Convertim to time format
                          *
                          * @param unix is time with long value
                          * @return string time
                          */
                          public static String convertUnix2Date(long unix) {
                          if (unix == 0) return "";
                          String result;
                          Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
                          @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
                          f.setTimeZone(TimeZone.getDefault());
                          result = f.format(date);
                          return result;
                          }

                          /**
                          * Handling the keyboard on device
                          *
                          * @param activity
                          */
                          private static void hideSoftKeyboard(Activity activity) {
                          InputMethodManager inputMethodManager =
                          (InputMethodManager) activity.getSystemService(
                          Activity.INPUT_METHOD_SERVICE);
                          if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
                          inputMethodManager.hideSoftInputFromWindow(
                          activity.getCurrentFocus().getWindowToken(), 0);
                          }
                          }

                          /**
                          * Handling the listener to dismiss the keyboard on device
                          *
                          * @param context <br>
                          * @param view is parent view <br>
                          */
                          public static void setupDismissKeyboardListener(Context context, View view) {

                          // Set up touch listener for non-text box views to hide keyboard.
                          if (!(view instanceof EditText)) {
                          view.setOnTouchListener((v, event) -> {
                          hideSoftKeyboard((Activity) context);
                          return false;
                          });
                          }

                          //If a layout container, iterate over children and seed recursion.
                          if (view instanceof ViewGroup) {
                          for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                          View innerView = ((ViewGroup) view).getChildAt(i);
                          setupDismissKeyboardListener(context, innerView);
                          }
                          }
                          }


                          /**
                          * Converting the DP value to PX to display on device
                          *
                          * @param context <br>
                          * @param value is DP value
                          * @return PX value
                          */
                          public static int parseFromDPtoPX(Context context, float value) {
                          Resources resources = context.getResources();
                          return (int) TypedValue.applyDimension(
                          TypedValue.COMPLEX_UNIT_DIP,
                          value,
                          resources.getDisplayMetrics()
                          );
                          }


                          public static void setupUI(View view, final Activity activity) {
                          //Set up touch listener for non-text box views to hide keyboard.
                          if(!(view instanceof EditText)) {
                          view.setOnTouchListener((v, event) -> {
                          hideSoftKeyboard(activity);
                          return false;
                          });
                          }

                          //If a layout container, iterate over children and seed recursion.
                          if (view instanceof ViewGroup) {
                          for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                          View innerView = ((ViewGroup) view).getChildAt(i);
                          setupUI(innerView, activity);
                          }
                          }
                          }


                          /**
                          *
                          */
                          protected Utils() {

                          }

                          public static final String TAG = "Utils";
                          public static final int DEFAULT_BUFFER_SIZE = 8192;
                          private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$";

                          /**
                          * @return true if JellyBean or higher
                          */
                          public static boolean isJellyBeanOrHigher() {
                          return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
                          }

                          /**
                          * @return true if Ice Cream or higher
                          */
                          public static boolean isICSOrHigher() {
                          return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
                          }

                          /**
                          * @return true if HoneyComb or higher
                          */
                          public static boolean isHoneycombOrHigher() {
                          return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
                          }

                          /**
                          * @return true if GingerBreak or higher
                          */
                          public static boolean isGingerbreadOrHigher() {
                          return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
                          }

                          /**
                          * @return true if Froyo or higher
                          */
                          public static boolean isFroyoOrHigher() {
                          return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
                          }

                          /**
                          * Check SdCard
                          *
                          * @return true if External Strorage available
                          */
                          public static boolean isExtStorageAvailable() {
                          return Environment.MEDIA_MOUNTED.equals(Environment
                          .getExternalStorageState());
                          }

                          /**
                          * Check internet
                          *
                          * @param context
                          * @return true if Network connected
                          */
                          public static boolean isNetworkConnected(Context context) {
                          ConnectivityManager connectivityManager = (ConnectivityManager) context
                          .getSystemService(Context.CONNECTIVITY_SERVICE);
                          NetworkInfo activeNetworkInfo = connectivityManager
                          .getActiveNetworkInfo();
                          if (activeNetworkInfo != null) {
                          return activeNetworkInfo.isConnected();
                          }
                          return false;
                          }

                          /**
                          * Check wifi
                          *
                          * @param context
                          * @return true if Wifi connected
                          */
                          public static boolean isWifiConnected(Context context) {
                          ConnectivityManager connectivityManager = (ConnectivityManager) context
                          .getSystemService(Context.CONNECTIVITY_SERVICE);
                          NetworkInfo wifiNetworkInfo = connectivityManager
                          .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                          if (wifiNetworkInfo != null) {
                          return wifiNetworkInfo.isConnected();
                          }
                          return false;
                          }

                          /**
                          * Check on/off gps
                          *
                          * @return true if GPS available
                          */
                          public static boolean checkAvailableGps(Context context) {
                          LocationManager manager = (LocationManager) context
                          .getSystemService(Context.LOCATION_SERVICE);

                          return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                          }

                          /**
                          * Download data url
                          *
                          * @param urlString
                          * @return InputStream
                          * @throws IOException IOException
                          */


                          /**
                          * @return an {@link HttpURLConnection} using sensible default settings for
                          * mobile and taking care of buggy behavior prior to Froyo.
                          * @throws IOException exception
                          */
                          public static HttpURLConnection buildHttpUrlConnection(String urlString)
                          throws IOException {
                          Utils.disableConnectionReuseIfNecessary();

                          URL url = new URL(urlString);

                          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                          conn.setReadTimeout(10000 /* milliseconds */);
                          conn.setConnectTimeout(15000 /* milliseconds */);
                          conn.setDoInput(true);
                          conn.setRequestMethod("GET");
                          return conn;
                          }

                          /**
                          * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
                          * frustrating bugs. In particular, calling close() on a readable
                          * InputStream could poison the connection pool. Work around this by
                          * disabling connection pooling.
                          */
                          public static void disableConnectionReuseIfNecessary() {
                          // HTTP connection reuse which was buggy pre-froyo
                          if (!isFroyoOrHigher()) {
                          System.setProperty("http.keepAlive", "false");
                          }
                          }

                          /**
                          * Check an email is valid or not
                          *
                          * @param email the email need to check
                          * @return {@code true} if valid, {@code false} if invalid
                          */
                          public static boolean isValidEmail(Context context, String email) {
                          boolean result = false;
                          Pattern pt = Pattern.compile(sFormatEmail);
                          Matcher mt = pt.matcher(email);
                          if (mt.matches()) {
                          result = true;
                          }
                          return result;
                          }

                          /**
                          * A method to download json data from url
                          */
                          @SuppressWarnings("ThrowFromFinallyBlock")
                          public static String downloadUrl(String strUrl) throws IOException {
                          String data = "";
                          InputStream iStream = null;
                          HttpURLConnection urlConnection = null;
                          try {
                          URL url = new URL(strUrl);

                          // Creating an http connection to communicate with url
                          urlConnection = (HttpURLConnection) url.openConnection();

                          // Connecting to url
                          urlConnection.connect();

                          // Reading data from url
                          iStream = urlConnection.getInputStream();

                          BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                          StringBuilder sb = new StringBuilder();

                          String line;
                          while ((line = br.readLine()) != null) {
                          sb.append(line);
                          }

                          data = sb.toString();

                          br.close();

                          } catch (Exception e) {
                          Log.d("Exception", e.toString());
                          } finally {
                          assert iStream != null;
                          iStream.close();
                          urlConnection.disconnect();
                          }
                          return data;
                          }


                          }



                          hope will be helpful





                          share








                          New contributor




                          Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                          Check out our Code of Conduct.






                          $endgroup$
















                            0












                            0








                            0





                            $begingroup$

                            imports



                             import android.annotation.SuppressLint;
                            import android.app.Activity;
                            import android.app.AlertDialog;
                            import android.content.Context;
                            import android.content.DialogInterface;
                            import android.content.Intent;
                            import android.content.res.Resources;
                            import android.location.LocationManager;
                            import android.net.ConnectivityManager;
                            import android.net.NetworkInfo;
                            import android.net.Uri;
                            import android.os.Build;
                            import android.os.Environment;
                            import android.provider.MediaStore;
                            import android.util.Log;
                            import android.util.TypedValue;
                            import android.view.View;
                            import android.view.ViewGroup;
                            import android.view.inputmethod.InputMethodManager;
                            import android.widget.EditText;

                            import java.io.BufferedReader;
                            import java.io.File;
                            import java.io.IOException;
                            import java.io.InputStream;
                            import java.io.InputStreamReader;
                            import java.net.HttpURLConnection;
                            import java.net.URL;
                            import java.text.SimpleDateFormat;
                            import java.util.Date;
                            import java.util.TimeZone;
                            import java.util.concurrent.TimeUnit;
                            import java.util.regex.Matcher;
                            import java.util.regex.Pattern;


                            class is here



                            public class Utils {
                            /**
                            * Convertim to time format
                            *
                            * @param unix is time with long value
                            * @return string time
                            */
                            public static String convertUnix2Date(long unix) {
                            if (unix == 0) return "";
                            String result;
                            Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
                            f.setTimeZone(TimeZone.getDefault());
                            result = f.format(date);
                            return result;
                            }

                            /**
                            * Handling the keyboard on device
                            *
                            * @param activity
                            */
                            private static void hideSoftKeyboard(Activity activity) {
                            InputMethodManager inputMethodManager =
                            (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
                            if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
                            inputMethodManager.hideSoftInputFromWindow(
                            activity.getCurrentFocus().getWindowToken(), 0);
                            }
                            }

                            /**
                            * Handling the listener to dismiss the keyboard on device
                            *
                            * @param context <br>
                            * @param view is parent view <br>
                            */
                            public static void setupDismissKeyboardListener(Context context, View view) {

                            // Set up touch listener for non-text box views to hide keyboard.
                            if (!(view instanceof EditText)) {
                            view.setOnTouchListener((v, event) -> {
                            hideSoftKeyboard((Activity) context);
                            return false;
                            });
                            }

                            //If a layout container, iterate over children and seed recursion.
                            if (view instanceof ViewGroup) {
                            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                            View innerView = ((ViewGroup) view).getChildAt(i);
                            setupDismissKeyboardListener(context, innerView);
                            }
                            }
                            }


                            /**
                            * Converting the DP value to PX to display on device
                            *
                            * @param context <br>
                            * @param value is DP value
                            * @return PX value
                            */
                            public static int parseFromDPtoPX(Context context, float value) {
                            Resources resources = context.getResources();
                            return (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP,
                            value,
                            resources.getDisplayMetrics()
                            );
                            }


                            public static void setupUI(View view, final Activity activity) {
                            //Set up touch listener for non-text box views to hide keyboard.
                            if(!(view instanceof EditText)) {
                            view.setOnTouchListener((v, event) -> {
                            hideSoftKeyboard(activity);
                            return false;
                            });
                            }

                            //If a layout container, iterate over children and seed recursion.
                            if (view instanceof ViewGroup) {
                            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                            View innerView = ((ViewGroup) view).getChildAt(i);
                            setupUI(innerView, activity);
                            }
                            }
                            }


                            /**
                            *
                            */
                            protected Utils() {

                            }

                            public static final String TAG = "Utils";
                            public static final int DEFAULT_BUFFER_SIZE = 8192;
                            private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$";

                            /**
                            * @return true if JellyBean or higher
                            */
                            public static boolean isJellyBeanOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
                            }

                            /**
                            * @return true if Ice Cream or higher
                            */
                            public static boolean isICSOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
                            }

                            /**
                            * @return true if HoneyComb or higher
                            */
                            public static boolean isHoneycombOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
                            }

                            /**
                            * @return true if GingerBreak or higher
                            */
                            public static boolean isGingerbreadOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
                            }

                            /**
                            * @return true if Froyo or higher
                            */
                            public static boolean isFroyoOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
                            }

                            /**
                            * Check SdCard
                            *
                            * @return true if External Strorage available
                            */
                            public static boolean isExtStorageAvailable() {
                            return Environment.MEDIA_MOUNTED.equals(Environment
                            .getExternalStorageState());
                            }

                            /**
                            * Check internet
                            *
                            * @param context
                            * @return true if Network connected
                            */
                            public static boolean isNetworkConnected(Context context) {
                            ConnectivityManager connectivityManager = (ConnectivityManager) context
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetworkInfo = connectivityManager
                            .getActiveNetworkInfo();
                            if (activeNetworkInfo != null) {
                            return activeNetworkInfo.isConnected();
                            }
                            return false;
                            }

                            /**
                            * Check wifi
                            *
                            * @param context
                            * @return true if Wifi connected
                            */
                            public static boolean isWifiConnected(Context context) {
                            ConnectivityManager connectivityManager = (ConnectivityManager) context
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo wifiNetworkInfo = connectivityManager
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                            if (wifiNetworkInfo != null) {
                            return wifiNetworkInfo.isConnected();
                            }
                            return false;
                            }

                            /**
                            * Check on/off gps
                            *
                            * @return true if GPS available
                            */
                            public static boolean checkAvailableGps(Context context) {
                            LocationManager manager = (LocationManager) context
                            .getSystemService(Context.LOCATION_SERVICE);

                            return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                            }

                            /**
                            * Download data url
                            *
                            * @param urlString
                            * @return InputStream
                            * @throws IOException IOException
                            */


                            /**
                            * @return an {@link HttpURLConnection} using sensible default settings for
                            * mobile and taking care of buggy behavior prior to Froyo.
                            * @throws IOException exception
                            */
                            public static HttpURLConnection buildHttpUrlConnection(String urlString)
                            throws IOException {
                            Utils.disableConnectionReuseIfNecessary();

                            URL url = new URL(urlString);

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setReadTimeout(10000 /* milliseconds */);
                            conn.setConnectTimeout(15000 /* milliseconds */);
                            conn.setDoInput(true);
                            conn.setRequestMethod("GET");
                            return conn;
                            }

                            /**
                            * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
                            * frustrating bugs. In particular, calling close() on a readable
                            * InputStream could poison the connection pool. Work around this by
                            * disabling connection pooling.
                            */
                            public static void disableConnectionReuseIfNecessary() {
                            // HTTP connection reuse which was buggy pre-froyo
                            if (!isFroyoOrHigher()) {
                            System.setProperty("http.keepAlive", "false");
                            }
                            }

                            /**
                            * Check an email is valid or not
                            *
                            * @param email the email need to check
                            * @return {@code true} if valid, {@code false} if invalid
                            */
                            public static boolean isValidEmail(Context context, String email) {
                            boolean result = false;
                            Pattern pt = Pattern.compile(sFormatEmail);
                            Matcher mt = pt.matcher(email);
                            if (mt.matches()) {
                            result = true;
                            }
                            return result;
                            }

                            /**
                            * A method to download json data from url
                            */
                            @SuppressWarnings("ThrowFromFinallyBlock")
                            public static String downloadUrl(String strUrl) throws IOException {
                            String data = "";
                            InputStream iStream = null;
                            HttpURLConnection urlConnection = null;
                            try {
                            URL url = new URL(strUrl);

                            // Creating an http connection to communicate with url
                            urlConnection = (HttpURLConnection) url.openConnection();

                            // Connecting to url
                            urlConnection.connect();

                            // Reading data from url
                            iStream = urlConnection.getInputStream();

                            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                            StringBuilder sb = new StringBuilder();

                            String line;
                            while ((line = br.readLine()) != null) {
                            sb.append(line);
                            }

                            data = sb.toString();

                            br.close();

                            } catch (Exception e) {
                            Log.d("Exception", e.toString());
                            } finally {
                            assert iStream != null;
                            iStream.close();
                            urlConnection.disconnect();
                            }
                            return data;
                            }


                            }



                            hope will be helpful





                            share








                            New contributor




                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






                            $endgroup$



                            imports



                             import android.annotation.SuppressLint;
                            import android.app.Activity;
                            import android.app.AlertDialog;
                            import android.content.Context;
                            import android.content.DialogInterface;
                            import android.content.Intent;
                            import android.content.res.Resources;
                            import android.location.LocationManager;
                            import android.net.ConnectivityManager;
                            import android.net.NetworkInfo;
                            import android.net.Uri;
                            import android.os.Build;
                            import android.os.Environment;
                            import android.provider.MediaStore;
                            import android.util.Log;
                            import android.util.TypedValue;
                            import android.view.View;
                            import android.view.ViewGroup;
                            import android.view.inputmethod.InputMethodManager;
                            import android.widget.EditText;

                            import java.io.BufferedReader;
                            import java.io.File;
                            import java.io.IOException;
                            import java.io.InputStream;
                            import java.io.InputStreamReader;
                            import java.net.HttpURLConnection;
                            import java.net.URL;
                            import java.text.SimpleDateFormat;
                            import java.util.Date;
                            import java.util.TimeZone;
                            import java.util.concurrent.TimeUnit;
                            import java.util.regex.Matcher;
                            import java.util.regex.Pattern;


                            class is here



                            public class Utils {
                            /**
                            * Convertim to time format
                            *
                            * @param unix is time with long value
                            * @return string time
                            */
                            public static String convertUnix2Date(long unix) {
                            if (unix == 0) return "";
                            String result;
                            Date date = new Date(TimeUnit.SECONDS.toMillis(unix));
                            @SuppressLint("SimpleDateFormat") SimpleDateFormat f = new SimpleDateFormat("HH:mm");
                            f.setTimeZone(TimeZone.getDefault());
                            result = f.format(date);
                            return result;
                            }

                            /**
                            * Handling the keyboard on device
                            *
                            * @param activity
                            */
                            private static void hideSoftKeyboard(Activity activity) {
                            InputMethodManager inputMethodManager =
                            (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
                            if (activity.getCurrentFocus() != null && activity.getCurrentFocus().getWindowToken() != null) {
                            inputMethodManager.hideSoftInputFromWindow(
                            activity.getCurrentFocus().getWindowToken(), 0);
                            }
                            }

                            /**
                            * Handling the listener to dismiss the keyboard on device
                            *
                            * @param context <br>
                            * @param view is parent view <br>
                            */
                            public static void setupDismissKeyboardListener(Context context, View view) {

                            // Set up touch listener for non-text box views to hide keyboard.
                            if (!(view instanceof EditText)) {
                            view.setOnTouchListener((v, event) -> {
                            hideSoftKeyboard((Activity) context);
                            return false;
                            });
                            }

                            //If a layout container, iterate over children and seed recursion.
                            if (view instanceof ViewGroup) {
                            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                            View innerView = ((ViewGroup) view).getChildAt(i);
                            setupDismissKeyboardListener(context, innerView);
                            }
                            }
                            }


                            /**
                            * Converting the DP value to PX to display on device
                            *
                            * @param context <br>
                            * @param value is DP value
                            * @return PX value
                            */
                            public static int parseFromDPtoPX(Context context, float value) {
                            Resources resources = context.getResources();
                            return (int) TypedValue.applyDimension(
                            TypedValue.COMPLEX_UNIT_DIP,
                            value,
                            resources.getDisplayMetrics()
                            );
                            }


                            public static void setupUI(View view, final Activity activity) {
                            //Set up touch listener for non-text box views to hide keyboard.
                            if(!(view instanceof EditText)) {
                            view.setOnTouchListener((v, event) -> {
                            hideSoftKeyboard(activity);
                            return false;
                            });
                            }

                            //If a layout container, iterate over children and seed recursion.
                            if (view instanceof ViewGroup) {
                            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                            View innerView = ((ViewGroup) view).getChildAt(i);
                            setupUI(innerView, activity);
                            }
                            }
                            }


                            /**
                            *
                            */
                            protected Utils() {

                            }

                            public static final String TAG = "Utils";
                            public static final int DEFAULT_BUFFER_SIZE = 8192;
                            private static String sFormatEmail = "^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+\.[a-zA-Z]{2,4}$";

                            /**
                            * @return true if JellyBean or higher
                            */
                            public static boolean isJellyBeanOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN;
                            }

                            /**
                            * @return true if Ice Cream or higher
                            */
                            public static boolean isICSOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
                            }

                            /**
                            * @return true if HoneyComb or higher
                            */
                            public static boolean isHoneycombOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB;
                            }

                            /**
                            * @return true if GingerBreak or higher
                            */
                            public static boolean isGingerbreadOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD;
                            }

                            /**
                            * @return true if Froyo or higher
                            */
                            public static boolean isFroyoOrHigher() {
                            return Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO;
                            }

                            /**
                            * Check SdCard
                            *
                            * @return true if External Strorage available
                            */
                            public static boolean isExtStorageAvailable() {
                            return Environment.MEDIA_MOUNTED.equals(Environment
                            .getExternalStorageState());
                            }

                            /**
                            * Check internet
                            *
                            * @param context
                            * @return true if Network connected
                            */
                            public static boolean isNetworkConnected(Context context) {
                            ConnectivityManager connectivityManager = (ConnectivityManager) context
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo activeNetworkInfo = connectivityManager
                            .getActiveNetworkInfo();
                            if (activeNetworkInfo != null) {
                            return activeNetworkInfo.isConnected();
                            }
                            return false;
                            }

                            /**
                            * Check wifi
                            *
                            * @param context
                            * @return true if Wifi connected
                            */
                            public static boolean isWifiConnected(Context context) {
                            ConnectivityManager connectivityManager = (ConnectivityManager) context
                            .getSystemService(Context.CONNECTIVITY_SERVICE);
                            NetworkInfo wifiNetworkInfo = connectivityManager
                            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                            if (wifiNetworkInfo != null) {
                            return wifiNetworkInfo.isConnected();
                            }
                            return false;
                            }

                            /**
                            * Check on/off gps
                            *
                            * @return true if GPS available
                            */
                            public static boolean checkAvailableGps(Context context) {
                            LocationManager manager = (LocationManager) context
                            .getSystemService(Context.LOCATION_SERVICE);

                            return manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
                            }

                            /**
                            * Download data url
                            *
                            * @param urlString
                            * @return InputStream
                            * @throws IOException IOException
                            */


                            /**
                            * @return an {@link HttpURLConnection} using sensible default settings for
                            * mobile and taking care of buggy behavior prior to Froyo.
                            * @throws IOException exception
                            */
                            public static HttpURLConnection buildHttpUrlConnection(String urlString)
                            throws IOException {
                            Utils.disableConnectionReuseIfNecessary();

                            URL url = new URL(urlString);

                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                            conn.setReadTimeout(10000 /* milliseconds */);
                            conn.setConnectTimeout(15000 /* milliseconds */);
                            conn.setDoInput(true);
                            conn.setRequestMethod("GET");
                            return conn;
                            }

                            /**
                            * Prior to Android 2.2 (Froyo), {@link HttpURLConnection} had some
                            * frustrating bugs. In particular, calling close() on a readable
                            * InputStream could poison the connection pool. Work around this by
                            * disabling connection pooling.
                            */
                            public static void disableConnectionReuseIfNecessary() {
                            // HTTP connection reuse which was buggy pre-froyo
                            if (!isFroyoOrHigher()) {
                            System.setProperty("http.keepAlive", "false");
                            }
                            }

                            /**
                            * Check an email is valid or not
                            *
                            * @param email the email need to check
                            * @return {@code true} if valid, {@code false} if invalid
                            */
                            public static boolean isValidEmail(Context context, String email) {
                            boolean result = false;
                            Pattern pt = Pattern.compile(sFormatEmail);
                            Matcher mt = pt.matcher(email);
                            if (mt.matches()) {
                            result = true;
                            }
                            return result;
                            }

                            /**
                            * A method to download json data from url
                            */
                            @SuppressWarnings("ThrowFromFinallyBlock")
                            public static String downloadUrl(String strUrl) throws IOException {
                            String data = "";
                            InputStream iStream = null;
                            HttpURLConnection urlConnection = null;
                            try {
                            URL url = new URL(strUrl);

                            // Creating an http connection to communicate with url
                            urlConnection = (HttpURLConnection) url.openConnection();

                            // Connecting to url
                            urlConnection.connect();

                            // Reading data from url
                            iStream = urlConnection.getInputStream();

                            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

                            StringBuilder sb = new StringBuilder();

                            String line;
                            while ((line = br.readLine()) != null) {
                            sb.append(line);
                            }

                            data = sb.toString();

                            br.close();

                            } catch (Exception e) {
                            Log.d("Exception", e.toString());
                            } finally {
                            assert iStream != null;
                            iStream.close();
                            urlConnection.disconnect();
                            }
                            return data;
                            }


                            }



                            hope will be helpful






                            share








                            New contributor




                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.








                            share


                            share






                            New contributor




                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.









                            answered 46 secs ago









                            Tlzdeveloper786Tlzdeveloper786

                            1




                            1




                            New contributor




                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.





                            New contributor





                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






                            Tlzdeveloper786 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                            Check out our Code of Conduct.






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Code Review Stack Exchange!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                Use MathJax to format equations. MathJax reference.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f109105%2fandroid-utils-class%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

                                Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

                                Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...