I have an activity which seems to be leaking memory, as shown below. However, leak canary does not seem to give any leaks or notifications. If I force garbage collection it does almost nothing.
In the activity I am creating imageviews and layouts dynamically, then putting them in a scrollview. An exmaple of this is below:
dynamicUI = new DynamicUI(getApplicationContext());
TextView textViewTitle = dynamicUI.headerTextView(exercises[i].name);
// Horizontal layout with tools icon and exercise time text
LinearLayout layoutTime = new LinearLayout(new ContextThemeWrapper(this, R.style.exercise_info_layout), null, 0);
layoutTime.addView(dynamicUI.iconImage(R.drawable.tools_icon));
layoutTime.addView(dynamicUI.captionTextView(exercises[i].time));
layoutTime.setGravity(Gravity.START | Gravity.CENTER_VERTICAL);
DynamicUI is a class I wrote to generate the views the same way throughout my app. Here is an example method:
public ImageView iconImage(int id){
ImageView imageView = new ImageView(new ContextThemeWrapper(context, R.style.ButtonImageSmall));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams((int) (50 * scale), (int) (50 * scale));
lp.setMargins((int) (10*scale), (int) (10*scale), (int) (10*scale), (int) (10*scale));
imageView.setLayoutParams(lp);
imageView.setImageDrawable(context.getResources().getDrawable(id));
return imageView;
}
There are several views which I add to the scrollview's child:
LinearLayout layoutVertical = dynamicUI.exerciseContainer();
layoutVertical.addView(textViewTitle);
layoutVertical.addView(imageViewCover);
layoutVertical.addView(layoutTime);
layoutVertical.addView(layoutDiff);
scrollLayoutChild.addView(layoutVertical);
There are quite a few of these layouts, 1-5 or so. They are generated from an SQLite database:
DatabaseHelper db = new DatabaseHelper(getApplicationContext());
I have tried assinging null to both my db and dynamicUI objects at the end of onCreate() and it doesn't seem to do anything:
// stop memory leak?
dynamicUI = null;
db = null;
You should never use the Application Context to create views. You should be using the Activity context of the activity that displays the view. That's because the views are scoped to the activity I don't know that that's your memory leak, but its definitely a mistake that can lead to odd behavior. At a minimum its themes and resources may not be correct.