Reputation: 1729
The following code is leaking the activity context:
This is actually inside an asyncTask in the onPostExecute
ChatCustomAdapter customAdapter = new ChatCustomAdapter(mContext, chatData, Typeface.createFromAsset(getAssets(), "font/Helvetica-Bold.ttf"));
mChatList.setAdapter(customAdapter);
inside the adapter the context is used for
inflater = LayoutInflater.from(mContext);
Am I holding a reference to the context? if so how do I release it?
LeakCanary is telling me that the ListView (mChatList) is leaking the context and if i remove setAdapter the leak has gone.
Upvotes: 1
Views: 559
Reputation: 1729
ok so i have found the problem but i do not understand it so maybe some can comment and explain or answer with why it does this. the leak was in the Chat activity. to get to the Chat activity i have a button in the previous activity:
ChatButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
Intent intent = new Intent(mContext, Chat.class);
mContext.startActivity(intent);
}
});
when i start the activity i was starting it from
mContext.startActivity(intent)
if i change this to just
startActivity(intent);
it doesn't leak.
Edit
it does still leak
Upvotes: 0
Reputation: 3054
EDIT:
You can try to wrap your mChatList
with WeakReference
, for exp:
class ChatTask extends AsyncTask {
private WeakReference<ListView> mListRef;
public ChatTask(ListView chatList) {
mListRef = new WeakReference<ListView>(chatList);
}
public void onPostExecute() {
ListView chatList = mListRef.get();
if (chatList != null) {
Context context = chatList.getContext();
ChatCustomAdapter customAdapter = new ChatCustomAdapter(context, chatData,
Typeface.createFromAsset(context.getAssets(), "font/Helvetica-Bold.ttf"));
chatList.setAdapter(customAdapter);
}
}
}
If it still not work, you could try to follow this post
I assume that you create the inflater
inside the ChatCustomAdapter
constructor and keep that inflater
as global variable to use later in getView
method?
If that true, I think you should try to remove the variable inflater
and inside getView
method, create a local inflater
by LayoutInflater.from(parentView.getContext);
Hope that helps.
Upvotes: 1