Android Singleton class to make it use of globally in application

In every Android app it's very common to to use to common methods like to show toast, loading dialog, show alert, get date and time etc..

Here I mentioned some of the methods which are commonly used:

  1. Showing toast
  2. Showing loading dialog
  3. Hiding loading dialog 
  4. Showing Alert Dialog
  5. Showing Snackbar
  6. Listen network connectivity
  7. Save image in device
  8. Get current date time
  9. To check app having required permissions or not

etc..

In your AppApplication class means which extends the class Application you can put the follwing code to make use it globally in application.

Here every method has `public` and `static` access modifiers so we can use them directly with class name without creating instance for the class AppApplication by passing context and required parameters.

Example to show toast message in your Activity like:

AppApplication.showToast(this, "Welcome to Android Tips", 0);

here 0 --> means Length short and 1 --> means Length long, also you can pass gravity as next parameter.

1. To show toast message:


public static void showToast(Context context, final String msg, int duration) {
    toast = Toast.makeText(context, msg, duration);
    toast.setText(msg);
    toast.setDuration(duration);
    toast.setGravity(Gravity.CENTER, 0, 0);
    toast.show();
}

2. To show loading dialog:


public static SweetAlertDialog showLoading(Context context, String title) {
    pDialog = new SweetAlertDialog(context, SweetAlertDialog.PROGRESS_TYPE);
    pDialog.getProgressHelper().setBarColor(ContextCompat.getColor(context, R.color.colorAccent));
    pDialog.setTitleText(title);
    pDialog.setCancelable(true);
    pDialog.show();

    return pDialog;
}

3. To hide loading dialog:


public static void hideLoading(SweetAlertDialog pDialog) {
    if (pDialog != null && pDialog.isShowing()) {
        pDialog.dismiss();
    }
}

4. To show alert dialog:


public static void showAlertDialog(Context context, String title, String message) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context);
    builder.setTitle(title);
    builder.setMessage(message);
    final AlertDialog alertDialog = builder.create();
    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE,
            "OK", new DialogInterface.OnClickListener() {
                @Override                public void onClick(DialogInterface dialogInterface, int i) {
                    alertDialog.cancel();
                }
            });
    alertDialog.show();
}

5. To show snack bar:


public static void showSnack(final Context context, View view, boolean isConnected) {
    if (snackbar == null) {
        snackbar = Snackbar
                .make(view, context.getString(R.string.network_failure), Snackbar.LENGTH_INDEFINITE)
                .setAction("SETTINGS", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(android.provider.Settings.ACTION_SETTINGS);
                        context.startActivity(intent);
                    }
                });
        View sbView = snackbar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.WHITE);
    }

    if (!isConnected && !snackbar.isShown()) {
        snackbar.show();
    } else {
        snackbar.dismiss();
        snackbar = null;
    }
}


6. To listen network connectivity:


@Override
    public void onNetworkConnectionChanged(boolean isConnected) {
        if (isConnected) {
            offLine_ModeIV.setVisibility(View.GONE);
            online_ModeIV.setVisibility(View.VISIBLE);

            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
            if (Connectivity.isConnectedFast(this)) {
                startService(new Intent(this, SyncService.class));
            }
        } else {
            offLine_ModeIV.setVisibility(View.VISIBLE);
            online_ModeIV.setVisibility(View.GONE);
 
        }
    }

7. Save image in device:


public static void changeImageSizeAndSaveInDevice(Bitmap photo, Uri path) {
        FileOutputStream fOut;
        try {
            Bitmap mBitmap = Bitmap.createBitmap(photo);
            fOut = new FileOutputStream(path.getPath());
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
            fOut.flush();
            fOut.close();

//            photo.recycle();
//            out.recycle();
        } catch (Exception e) {
            Log.e("ImageSaveInLocal: ", e.toString());
            logFile.writeCrashLog("While resize image in Device : " + System.lineSeparator() + e.toString());
        }

    }

8. To get current date and time:


public static String getCurrentDateTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date date = new Date();
        return simpleDateFormat.format(date);
    }

9. To check app has required permissions:


public static boolean hasPermissions(Activity context, String... permissions) {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
            for (String permission : permissions) {
                if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(context, new String[]{permission}, 100);
                    return false;
                }
            }
        }
        return true;
    }

Note: Don't forget to create all global fields like:

private static Snackbar snackbar = null;
public static ProgressDialog pDialog;
private static Toast toast;

Comments

Post a Comment

Thank you will get back to you soon.

Popular posts from this blog

Android - Run app without USB cable every time

How to create a website as android app using web view in Kotlin language.