Search code examples
androidperformanceandroid-memory

Memory management tips on initialising variables?


I'm trying to reduce the risk of my app running into Memory Leaks, and i'm currently focusing on tiding up my initialisation of variables as a quick fix. For example,

public void renameItems(Activity activity, ...) {

AlertDialog.Builder builderInner = new AlertDialog.Builder(activity, R.style.MyAlertDialogStyle);

    LinearLayout layout = new LinearLayout(activity);
    final TextView itemTitle = new TextView(activity);
    final EditText itemTitleInput = new EditText(activity);
    final TextView subItem = new TextView(activity);
    final EditText subItemInput = new EditText(activity);

// Irrelevant code ...

} 

Whenever this method is called, are new instances of these variables being created each time? If so, how would i nullify them when im done?

I've also tried changing the scope of the variables, but i need to pass a context to them (which i receive from the method), and i'm unsure how i would do that on a global scale.


Solution

  • Maybe this isn't the exact answer to solution for the code to provided, but you asked for a general solution to handle/detect memory leask inside your application, right?

    The Godmaster Jake Wharton released a nice tool to detect potential memory leaks some time ago: It's called LeakCanary

    It's really easy to integrate in your app! (BUT BE CAREFUL NOT ADDING IT TO THE RELEASE BUILD!!!)

    On the github page it is described how to integrate LeakCanary to your app:

    In your build.gradle:

     dependencies {
       debugCompile 'com.squareup.leakcanary:leakcanary-android:1.4'
       releaseCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4'
       testCompile 'com.squareup.leakcanary:leakcanary-android-no-op:1.4'
     }
    

    In your Application class:

    public class ExampleApplication extends Application {
    
      @Override public void onCreate() {
        super.onCreate();
        LeakCanary.install(this);
      }
    }
    

    Sooooo... But now you have a leak and what next? From my personal experience be aware doing something like this:

    • try to avoid saving an Activity or an Activity context as a class member. Use always the application context instead, if it's possible!
    • try to avoid creating layout via runtime! Inflate them by using a xml-layout
    • if you are using EventBus, RxJava/RxAndroid, and so on: don't forget to unsubscribe from the tools/framworks/providers you are using. If they are not unsubscribed after the Activity runs into onPause() or onStop()
    • If you are really afraid of creating variables inside your method, try to avoid to create all variables at the top of a method, create them when you need them! In Java you don't have nullify/terminate them! That's why you have the Garbage Collection!