9

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
TMS
  • 1,201
  • 1
  • 13
  • 20
  • 2
    Actually, there's nothing wrong with your current code. It's true that you want to be careful when passing around `Activity` contexts, but in this scenario there are no static/long lived references that break the activity life cycle, and/or any long-running operations that may prevent a reference from being garbage collected. The summary in the link given by @agamov basically says it all. No need to clutter your code with `WeakReference` in this particular case though. – MH. Sep 18 '13 at 19:08

1 Answers1

6

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

agamov
  • 4,407
  • 1
  • 27
  • 31
  • Thank you for the quick response, can you give an example of how WeakReference must be implemented here? – TMS Sep 18 '13 at 07:29
  • 1
    Thanks for the detailed answer! Is this the correct way to use this from Activity? globalMethods.showSimpleAlertDialog(new WeakReference(this),R.string.error_msg_failed_load, true); – TMS Sep 18 '13 at 11:38
  • as for me it seems ok) – agamov Sep 18 '13 at 11:56
  • 5
    This is an old question/answer, but I wanted to add my 2 cents: I think, in the case of a static method, unless you are holding the reference beyond the scope of the method itself (passing the reference to another class that stores that reference in a static member variable, for instance), WeakReference is not necessary. – jkane001 Apr 12 '16 at 16:34
  • The question is an old one, but the search engine still gives as a result, which means it is always good to update the stuff with the new thoughts based on the practice which we get during the years. – X-HuMan May 31 '16 at 17:19
  • @jkane001 I was thinking about the same thing. Unless its the case you mentioned, what's the advantage of passing a weak reference to the util class method? – Shobhit Puri Aug 06 '17 at 23:43