Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing reference to activity to utility class android

I realise this question has been asked many times, but I am still unable to completely understand this concept. In my application, I am using a static utility class to keep common methods (like showing error dialogs)

Here is how my static class looks like:

    public class GlobalMethods {

//To show error messages
        public static final void showSimpleAlertDialog(final Activity activity, String  message, final boolean shouldFinishActivity) {

            if (!activity.isFinishing()) {

                AlertDialog.Builder builder = new AlertDialog.Builder(activity, AlertDialog.THEME_HOLO_DARK);
                builder.setCancelable(true).setMessage("\n" + message + "\n").setNeutralButton(activity.getResources().getString(R.string.label_ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.cancel();

                    }
                }).setOnCancelListener(new DialogInterface.OnCancelListener() {

                    @Override
                    public void onCancel(DialogInterface dialog) {
                        // TODO Auto-generated method stub
                        if (shouldFinishActivity)
                            activity.finish();
                    }
                }).show();
            }

        }

//check for connectivity
    public static final boolean isOnline(Context context) {
        NetworkInfo networkInfo = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
        return (networkInfo != null && networkInfo.isConnectedOrConnecting());
    }

//for the 'HOME' button on every activity
    public static final void goToDashboard(Activity activity) {
        goToActivity(ActivityDashboard.class, activity);

    }

    }

In my main activity, I call this function like this

GlobalMethods.showSimpleAlertDialog(this, R.string.error_msg_failed_load, true);

Is this a good approach? Does this cause memory leaks? If yes, please guide me on the best practices on using utility classes

like image 457
TMS Avatar asked Sep 18 '13 06:09

TMS


1 Answers

No, it's a bad approach. You better pass WeakReference<Activity> to your methods, and implement methods like this:

public static final void showSimpleAlertDialog(final WeakReference<Activity> mReference, String  message, final boolean shouldFinishActivity) {
    Activity activity = mReference.get();
    if (activity != null) {
        //your code goes here
    }

Further reading: http://android-developers.blogspot.ae/2009/01/avoiding-memory-leaks.html

like image 118
agamov Avatar answered Oct 17 '22 17:10

agamov