Android Utility

Utility is a class which contains some method , which is useful in whole app. its contain some information, detail, calculation validation etc.

Android Utility

Android Utility (Java/KOTLIN)

Utility is a class which contains some useful method or constants value, which is useful in whole app.  its contain some information, detail, calculation validation etc. We can place all same type of method in one class files which is not depended or related to any screens and also useful for many places.


AndroidUtility (Java and KOTLIN)

For Example: 

private boolean isNetworkConnected() {
  ConnectivityManager cm = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    return cm.getActiveNetworkInfo() != null;
}

So this method can use many places  and its not depended of any screens and pages. So same type of methods will place at one class that is Utils class.

Benifits of Utility :

- Easy to understand.

- Easy to modify and upgrade.

- Easy to fixed issues.

- Write once and use many place.

- Easy plugin and Play (Can use same file at many project without any changes.)

- It's not increase project complexity.

We can categorised Utils files with its category.

Example :

Logcat :

To print Log in android app, Create a files for logcat Log.java.

Lets create a class :

public class DNALog {
    private static String TAG = "datanapps";
    DNALog(){
        // nothing to do here
    }

    public static void d(String msg) {
        if (BuildConfig.DEBUG) {
            android.util.Log.d(TAG, validateString(msg));
        }
    }
    public static void e(String msg) {
        if (BuildConfig.DEBUG) {
            android.util.Log.e(TAG,  validateString(msg));
        }
    }
    public static void i(String msg) {
        if (BuildConfig.DEBUG) {
            android.util.Log.i(TAG,  validateString(msg));
        }
    }
    public static void v(String msg) {
        if (BuildConfig.DEBUG) {
            android.util.Log.v(TAG,  validateString(msg));
        }
    }
    private static String validateString(String msg){
      if(msg==null){
          return "null";
      }
     return msg;
    }
}

2. Snackbar :

public class DNASnackBar {
    DNASnackBar() {
        // nothing to do here
    }
    public static void show(Activity activity, String snackBarMsg) {
        if (activity != null) {
            Snackbar        .make(activity.getWindow().getDecorView().findViewById(android.R.id.content), validateString(snackBarMsg), Snackbar.LENGTH_LONG).show();
        }
    }

    /*
    * if you are passing context from some where then it will be show toast because snackbar can show only for activit
    * */
    public static void show(Context activity, String snackBarMsg) {

        if (activity != null) {
            if (activity instanceof Activity) {
                show((Activity) activity, snackBarMsg);
            } else {
                Toast.makeText(activity, validateString(snackBarMsg), Toast.LENGTH_LONG).show();
            }
        }
    }

    // for activity and action
    public static void show(Activity activity, String snackBarMsg, String actionText, View.OnClickListener clickListener) {
        if (activity != null) {
            Snackbar   .make(activity.getWindow().getDecorView().findViewById(android.R.id.content), validateString(snackBarMsg), Snackbar.LENGTH_LONG)
                    .setAction(actionText, clickListener).show();
        }
    }

    // for view and action
    public static void show(View view, String snackBarMsg, String actionText, View.OnClickListener clickListener) {
        if (view != null) {
            Snackbar
                    .make(view, validateString(snackBarMsg), Snackbar.LENGTH_LONG)
                    .setAction(actionText, clickListener).show();
        }
    }
    }

3. Toast

public class DNAToast {
private static Toast toast;
    DNAToast() {
        // nothing to do here
    }

    public static void show(Context context, String msg) {
        if (context != null) {
            if (toast!= null) {
                toast.cancel();
            }
            toast= Toast.makeText(context, validateString(msg), getToastTime());
            toast.show();
        }
    }
    private static String validateString(String msg) {
        if (msg == null) {
            return "null";
        }
        return msg;
    }
   private static int getToastTime(){
        return Toast.LENGTH_LONG;
    }
}

 

4. CollectionUtils

public final class DNACollectionUtils {

    private DNACollectionUtils() {
        // nothing to do here
    }
    public static boolean isNotEmpty(Collection<?> collection) {
        return !isEmpty(collection);
    }
    public static boolean isEmpty(Collection<?> collection) {
        return collection == null || collection.isEmpty();
    }
    public static boolean isNull(Collection<?> collection) {
        return collection == null;
    }
    public static int size(Collection<?> collection) {
        if (collection == null)
            return 0;

        return collection.isEmpty()?0:collection.size();
    }
}

5. AppUtils

public class DNAAppUtils {

    DNAAppUtils() {
        // nothing to do here
    }
    public static String getAppVersionName() {
        return BuildConfig.VERSION_NAME;
    }
    public static int getAppVersionCode() {
        return BuildConfig.VERSION_CODE;
    }
    public static String getApplicationId() {
        return BuildConfig.APPLICATION_ID;
    }
    public static String getApplicationPackageName() {
        return getApplicationId();
    }
    public static String getBuildType() {
        return BuildConfig.BUILD_TYPE;
    }
    public static boolean isBuildType() {
        return BuildConfig.DEBUG;
    }
}

6. DateUtils:

public class DNADateUtils {
    private DNADateUtils() {
        // nothing to do here
    }
    // time
    public static final String DATE_FORMAT_HH_mm = "HH:mm"; // 23:30
    public static final String DATE_FORMAT_hh_mm = "hh:mm"; // 12:30
    public static final String DATE_FORMAT_hh_mm_ss = "hh:mm:ss"; // 12:30:30
    public static final String DATE_FORMAT_hh_mm_ss_aa = "hh:mm:ss aa";
    public static final String DATE_FORMAT_hh_mm_aa = "hh:mm aa"; 
// date
    public static final String DATE_FORMAT_yyyy_dd_MM = "yyyy, dd MMM";
    public static final String DATE_FORMAT_yyyy_MM_dd = "yyyy-MM-dd"; 
    public static final String DATE_FORMAT_yyyyMMdd = "yyyyMMdd"; // 19891231
    public static final String DATE_FORMAT_ddMMyyyy = "ddMMyyyy"; // 31121989
    public static final String DATE_FORMAT_dd_MM_yyyy = "dd-MM-yyyy"; 

// date time
    public static final String DATE_FORMAT_dd_MM_yyyy_hh_mm_ss = "dd-MM-yyyy hh:mm:ss"; 
    public static final String DATE_FORMAT_dd_MM_yyyy_hh_mm = "dd-MM-yyyy hh:mm"; 
    public static final String DATE_FORMAT_dd_MM_yyyy_hh_mm_aa = "dd-MM-yyyy hh:mm aa"; 
    public static final String DATE_FORMAT_MMM_dd_yyyy_hh_aa = "MMM dd, yyyy hh aa"; 
    public static String getCurrentDate(String format) {
        if (TextUtils.isEmpty(format)) {
            format = DATE_FORMAT_dd_MM_yyyy_hh_mm;
        }
        return DateFormat.format(format, new java.util.Date()).toString();
    }

    public static String formatDate(String format, long timeStamp) {
        if (timeStamp <= 0) {
            timeStamp = System.currentTimeMillis();
        }

        return DateFormat.format(format, new java.util.Date(timeStamp)).toString();
    }

    public static String formatDate(String format, Date date) {
        return DateFormat.format(format, date == null ? new Date() : date).toString();
    }

    public static String formatDate(String format, Calendar calendar) {
        return DateFormat.format(format, calendar == null ? Calendar.getInstance().getTime() : calendar.getTime()).toString();
    }

    /*
    *
    * It's return date  before one week timestamp
    *
    *  like return
    *
    *  1 day ago
    *  2 days ago
    *  5 days ago
    *  21 April 2019
    *
    *
    * */
    public static String getTimeAgoDate(long pastTimeStamp) {
        // for 2 min ago   use  DateUtils.MINUTE_IN_MILLIS
        // for 2 sec ago   use  DateUtils.SECOND_IN_MILLIS
        // for 1 hours ago use  DateUtils.HOUR_IN_MILLIS
        long now = System.currentTimeMillis();

        if (now - pastTimeStamp < 1000) {
            pastTimeStamp = pastTimeStamp + 1000;
        }
        CharSequence ago =
                DateUtils.getRelativeTimeSpanString(pastTimeStamp, now, DateUtils.SECOND_IN_MILLIS);
        return ago.toString();
    }

    /*
     *
     * It's return date  before one week timestamp
     *
     *  like return
     *
     *  1 day ago
     *  2 days ago
     *  5 days ago
     *  2 weeks ago
     *  2 months ago
     *  2 years ago
     *
     *
     * */

    public static String getTimeAgo(long mReferenceTime) {
        long now = System.currentTimeMillis();
        final long diff = now - mReferenceTime;
        if (diff < android.text.format.DateUtils.WEEK_IN_MILLIS) {
            return (diff <= 1000) ?
                    "just now" :
                    android.text.format.DateUtils.getRelativeTimeSpanString(mReferenceTime, now, DateUtils.MINUTE_IN_MILLIS,
                            DateUtils.FORMAT_ABBREV_RELATIVE).toString();
        } else if (diff <= 4 * android.text.format.DateUtils.WEEK_IN_MILLIS) {
            int week = (int)(diff / (android.text.format.DateUtils.WEEK_IN_MILLIS));
            return  week>1?week+" weeks ago":week+" week ago";
        } else if (diff < android.text.format.DateUtils.YEAR_IN_MILLIS) {
            int month = (int)(diff / (4 * android.text.format.DateUtils.WEEK_IN_MILLIS));
            return  month>1?month+" months ago":month+" month ago";
        } else {
            int year = (int) (diff/DateUtils.YEAR_IN_MILLIS);
            return year>1?year+" years ago":year+" year ago";
        }
    }
}

7. StringUtils

public class DNAStringUtils {
    /**
     * A String for a space character.
     */
    public static final String SPACE = " ";
    /**
     * The empty String {@code ""}.
     */
    public static final String EMPTY = "";
    /**
     * A String for line feed LF ("\n").
     */
    public static final String LF = "\n";
    /**
     * A String for carriage return CR ("\r").
     */
    public static final String CR = "\r";
    /**
     * A String for carriage return CR + LF ("\r\n").
     */
    public static final String CRLF = "\\r\\n";
    /**
     * A String for not Applicable
     */
    public static final String NA = "NA";
    public static boolean isEmpty(String str) {
        return TextUtils.isEmpty(str);
    }
    public static boolean isNotEmpty(String str) {
        return !TextUtils.isEmpty(str);
    }
    public static boolean isNull(String str) {
        return str == null;
    }
    public static int length(String str) {
        if (str == null)
            return 0;
        return str.isEmpty()?0:str.length();
    }
}

8. FileUtils

public class DNAFileUtils {
    // suffix jpg
    public static final String JPG = ".jpg";
    // suffix png
    public static final String PNG = ".png";
    public static boolean isFileExist(String filePath) {
        return filePath != null && new File(filePath).exists();
    }
    public static boolean isFileExist(File file) {
        return file != null && file.exists();
    }
  
    public static File createJPGImageFile(File dir) {
        try {
            File image = File.createTempFile(
                    "IMG_" + System.currentTimeMillis(),  /* prefix */
                    ".jpg",         /* suffix */
                    dir     /* directory */
            );
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /*
     * Create JPG image file
     * */
    public static File createFile(File dir, String suffix) {
        try {
            File image = File.createTempFile(
                    "IMG_" + System.currentTimeMillis(),  /* prefix */
                    suffix,         /* suffix */
                    dir     /* directory */
            );
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /*
     * Create mp4 file
     * */
    public static File createMp4File(File dir) {
        try {
            File image = File.createTempFile(
                    "IMG_" + System.currentTimeMillis(),  /* prefix */
                    ".mp4",         /* suffix */
                    dir     /* directory */
            );
            return image;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getFileSize(String filePath) {
        int fileSize = 0;
        if (filePath != null) {
            File file = new File(filePath);
            return getFileSize(file);
        }
        return fileSize + " KB";
    }
    public static String getFileSize(File file) {
        int fileSize = 0;
        if (file != null && file.exists()) {
            fileSize = Integer.parseInt(String.valueOf(file.length() / 1024));
            if (fileSize >= 1024) {
                return (fileSize / 1024) + " MB";
            } else {
                return fileSize + " KB";
            }
        }
        return fileSize + " KB";
    }
    //  // get file mime type
    public static String getMimeType(String filePath) {
        String type = null;
        String extension = MimeTypeMap.getFileExtensionFromUrl(filePath);
        if (extension != null) {
            type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        }
        return type;
    }
}

9. Shared Preference

public class DNASharedPreferenceUtils {
    private static SharedPreferences shared;
    private static Editor edit;
    private static String SHARED_PREFERENCE_NAME = "dna_shar_pref_name";
    public static void init(Context c) {
        init(c, SHARED_PREFERENCE_NAME, Context.MODE_PRIVATE);
    }
    public static void init(Context context, String preferenceName, int mode) {
        shared = context.getSharedPreferences(preferenceName,
                mode);
        edit = shared.edit();
        edit.apply();
    }
//==================================================================//
    public static void saveString(String key, String value) {
        edit.putString(key, value);
        edit.apply();
    }
    public static String getString(String key) {
        if (key != null) {
            return shared.getString(key, "");
        }
        return "";
    }
    public static String getString(String key, String defaultDesireValue) {
        if (key != null) {
            return shared.getString(key, defaultDesireValue);
        }
        return defaultDesireValue;
    }
//==================================================================//
    public static void saveInt(String key, int value) {
        edit.putInt(key, value);
        edit.apply();
    }
    public static int getInt(String key) {
        return shared.getInt(key, 0);
    }
    public static int getInt(String key, int defaultDesireValue) {
        return shared.getInt(key, defaultDesireValue);
    }

//==================================================================//
    public static void saveFloat(String key, float value) {
        edit.putFloat(key, value);
        edit.apply();
    }
    public static float getFloat(String key) {
        return shared.getFloat(key, 0);
    }
    public static float getFloat(String key, float defaultDesireValue) {
        return shared.getFloat(key, defaultDesireValue);
    }

//==================================================================//
    public static void saveLong(String key, long value) {
        edit.putLong(key, value);
        edit.apply();
    }
    public static long getLong(String key) {
        return shared.getLong(key, 0L);
    }
    public static long getLong(String key, long defaultDesireValue) {
        return shared.getLong(key, defaultDesireValue);
    }

//==================================================================//
    public static void saveBoolean(String key, boolean value) {
        edit.putBoolean(key, value);
        edit.apply();
    }
    public static boolean getBoolean(String key) {
        return shared.getBoolean(key, false);
    }
    public static boolean getBoolean(String key, boolean defaultDesireValue) {
        return shared.getBoolean(key, defaultDesireValue);
    }

    //==================================================================//
    public static boolean isExist(String key) {
        return shared.contains(key);
    }
    public static void remove(String key) {
        edit.remove(key);
        edit.apply();
    }
    public static void clearAllSharedPreferences() {
        edit.clear();
        edit.apply();
    }
}

 

10. ExceptionHandler

public class DNAExceptionHandler {
    DNAExceptionHandler() {
        // nothing to do here
    }
    public static void handleException(Exception e) {
        if (e != null) {
            Log.e("DNA", e.getMessage());
            //Crashlytics.logException(e);
        }
    }
    public static void handleException(Error e) {
        if (e != null) {
            Log.e("DNA", e.getMessage());
           // Crashlytics.logException(e);
        }
    }
    public static void handleException(String errorValue) {
        if (errorValue != null) {
            Log.e("DNA", errorValue);
            //Crashlytics.logException(e);
        }
    }
}

11. Device Detail

public class DNADeviceUtils {
    DNADeviceUtils() {
        // nothing to do here
    }
    public static String getSerial() {
        return Build.SERIAL;
    }
    public static String getModel() {
        return Build.MODEL;
    }
    public static String getDeviceId() {
        return Build.ID;
    }
    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }
    public static String getBrand() {
        return Build.BRAND;
    }
    public static String getType() {
        return Build.TYPE;
    }
    public static String getUser() {
        return Build.USER;
    }
    public static int getBaseVersionCode() {
        return Build.VERSION_CODES.BASE;
    }
    public static String getVersionIncremental() {
        return Build.VERSION.INCREMENTAL;
    }
    public static String getSDKVersion() {
        return Build.VERSION.SDK;
    }
    public static String getBoard() {
        return Build.BOARD;
    }

    public static String getDeviceHost() {
        return Build.HOST;
    }
    public static String getDeviceFingerprint() {
        return Build.FINGERPRINT;
    }
    public static String getVersionRelease() {
        return Build.VERSION.RELEASE;
    }
}

Please download project and sample here. Its have collection of all utils in JAVA/KOTLIN

AndroidUtility (Java and KOTLIN)

If you enjoyed this story, please click LIKE button and SHARE to help others find it!

I'm always trying to write a meaningful blogs but you can suggest me in comments for next topics.

Thank you so much, Have a great day !


Click Here To See More

What's Your Reaction?

like
0
dislike
0
love
0
funny
0
angry
0
sad
0
wow
3