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.
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:
onPause()
or onStop()