Code Snippets

Android Common Utils

This page is dedicated to the code snippets, yes a code snippets which we called Android common utils or utility functions or you can say some useful utils methods. I collected different methods from different famous projects and added here. Some of them i collected from the internet, some of them i wrote it my self. Any way i dedicated this page to You. I will add more messages in future as i will discover more and useful methods.

android common utils classes method utility

Category:

I have ordered these methods in category so you can reach according to your need.

Last Updated [September, 29 2017]

  • General
  • String Utils
  • Validation Utils
  • Keyboard
  • Dialogs
  • Network
  • Application
  • Map Utils

General Utils

Get Random Color


public static int getRandomColor() {

 Random random = new Random();
 int red = random.nextInt(255);
 int green = random.nextInt(255);
 int blue = random.nextInt(255);

 return Color.argb(255, red, green, blue);

}

Get Random String


private String getRandomString() {
    return UUID.randomUUID().toString();
}

Generate Hash Key


public static void generateHashkey(Context c,String Package){
    try {
        PackageInfo info = c.getPackageManager().getPackageInfo(
                Package ,
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());

            Log.d("KeyHash",Base64.encodeToString(md.digest(),
                    Base64.NO_WRAP));
            Log.d("Packege name",info.packageName);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.d("HashException", e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        Log.d("HashException", e.getMessage(), e);
    }
}

Get Device Id


public String getDeviceID(Context mcontext) {
    return Settings.Secure.getString(mcontext.getContentResolver(),
            Settings.Secure.ANDROID_ID);
}

Get IMEI Code


public String getIMEICode(Context mcontext) {
    TelephonyManager telephonyManager = (TelephonyManager) mcontext
            .getSystemService(Context.TELEPHONY_SERVICE);
    if (ActivityCompat.checkSelfPermission(mcontext, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return TODO;
    }
    return telephonyManager.getDeviceId();
}

String Utils

Capitalize First Letter


public static String capitalizeFirstLetter(String str) {
    if (str.isEmpty()) {
        return str;
    }
    char c = str.charAt(0);
    return (!Character.isLetter(c) || Character.isUpperCase(c)) ? str : new StringBuilder(str.length())
            .append(Character.toUpperCase(c)).append(str.substring(1)).toString();
}

Encrypt String


public String encryptString(String encryptKey, String value) {
    try {
        DESKeySpec keySpec = new DESKeySpec(encryptKey.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] clearText = value.getBytes("UTF8");
        // Cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
        return encrypedValue;

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return value;
}

Decrypt String


public String decryptString(String decryptKey, String value) {
    try {
        DESKeySpec keySpec = new DESKeySpec(decryptKey.getBytes("UTF8"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(keySpec);

        byte[] encrypedPwdBytes = Base64.decode(value, Base64.DEFAULT);
        // cipher is not thread safe
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypedValueBytes = (cipher.doFinal(encrypedPwdBytes));

        String decrypedValue = new String(decrypedValueBytes);
        return decrypedValue;

    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return value;
}

 

Validation Utils

Is Valid Email


public static boolean isValidEmail(String email) {

    if (email == null) {
        return false;
    }

    final String emailPattern = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    Matcher matcher;
    Pattern pattern = Pattern.compile(emailPattern);

    matcher = pattern.matcher(email);

    if (matcher != null) {
        return matcher.matches();
    } else {
        return false;
    }
}

Is Blank

 public static boolean isBlank(String str) {
    return (str == null || str.trim().length() == 0);
}

 

Keyboard Utils

Hide Keyboard


public static void hideKeyboard(Context context) {
    try {
        // use application level context to avoid unnecessary leaks.
        InputMethodManager inputManager = (InputMethodManager) context.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(((Activity) context).getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception e) {
        Log.e(TAG, "Bump, cant even hide keyboard " + e.getMessage());
    }
}
 

Show Keyboard


public static void showKeyboard(View view) {
    if (view == null) {
        return;
    }
    InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
}
 

 

Dialogs Utils

Show AlerDialog


public static void showAlertDialog(final Context c, String title, String message) {
    new AlertDialog.Builder(c).setTitle(title).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
        }
    }).show();
}

Show AlertDialog Without Cancel

 
public static void showAlertDialogWithoutCancel(final Context c, String title, String message) {
    new AlertDialog.Builder(c).setTitle(title).setMessage(message).setPositiveButton(android.R.string.ok, null).show();
}

Show AlertDialog With Finish Activity

public static void showAlertDialogWithFinishActivity(final Context c, String title, String message) {
    new AlertDialog.Builder(c).setTitle(title).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
            Activity a = (Activity) c;
            a.finish();

        }
    }).show();
}

Show AlertDialog With StartActivity


public static void showAlertDialogWithStartActivity(final Context c, String title, String message, final Class<?> cls) {
    new AlertDialog.Builder(c).setTitle(title).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

            dialog.dismiss();
            Activity a = (Activity) c;
            a.startActivity(new Intent(c, cls));

        }
    }).show();
}

Show ProgressDialog


//Will return instance on ProgressDialog to show and hide
public static ProgressDialog MorseProgressDialog(final Context ctx, @Nullable String _title, String _message/*, @DrawableRes @Nullable int icon*/) {

    ProgressDialog  pd = new ProgressDialog(ctx);
    pd.setTitle(_title);
    pd.setMessage(_message);
    pd.setIndeterminate(false);
    pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    pd.setCancelable(false);
    return pd;
}

 

Network Utils

Get Data Connection Type


public static int getDataConnectionType(Context ctx) {
    
    ConnectivityManager connectivityManager = (ConnectivityManager) ctx.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null && connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null) {
        if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected()) {
            //TYPE_MOBILE return = 0 => Connected With Data
            return ConnectivityManager.TYPE_MOBILE;
        } else if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected()) {
            //TYPE_MOBILE return = 1 => Connected With Wifi
            return ConnectivityManager.TYPE_WIFI;
        } else
            return -1;
    } else
        return -1;
}

Online When Connected To Wifi Only

  
private boolean OnlineWhenConnectedToWifiOnly(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    //Checking if your connected to Internet.
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {

        //Checking if you are connected to wifi.
        if(netInfo.getType() != ConnectivityManager.TYPE_WIFI) {
            Toast.makeText(context, "You must need to enable wifi in order to download", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }
    else {
        return false;
    }
}

Is Connected Online

   
private boolean isConnectedOnline(Context context) {

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    else {
        return false;
    }
}

Application Utils

Get OS Version


public static String getOsVersion() {
    return Build.VERSION.RELEASE;
}

Get Application Version Code


public static int getApplicationVersionCode(Context ctx) {

    int versionCode = 0;

    try {
        versionCode = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(), 0).versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    return versionCode;
}

Get Application Version Name


public static String getApplicationVersionNumber(Context context) {

    String versionName = null;

    if (context == null) {
        return versionName;
    }

    try {
        versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }

    return versionName;
}

So this is not end, i will add more useful methods in common utils in future 🙂 enjoy