2017-01-12 40 views
1

下面的代码正在泄漏的活动上下文:ListView的泄漏活动上下文

这实际上是一个的AsyncTask内部在适配器内部的上下文被用于

的onPostExecute

ChatCustomAdapter customAdapter = new ChatCustomAdapter(mContext, chatData, Typeface.createFromAsset(getAssets(), "font/Helvetica-Bold.ttf")); 
mChatList.setAdapter(customAdapter); 

inflater = LayoutInflater.from(mContext); 

我是否持有对上下文的引用?如果是这样,我该如何释放它?

LeakCanary告诉我,ListView(mChatList)正在泄漏上下文,如果我删除了setAdapter,泄漏消失了。

LeakCanary screen shot

+0

什么是“聊天实例”,它是保存上下文的引用的单身?如果是这样,将会有泄漏。 – WenChao

+0

@WenChao聊天是只使用适配器显示列表的活动,所以我推测它正在泄漏聊天活动的上下文 – Rob85

回答

1

编辑: 你可以尝试用WeakReference来包装你mChatList,为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); 
    } 
    } 
} 

如果还是不行,你可以尝试按照这个post


我假设你在内部创建了的构造函数并保留inflater作为全局变量,以便在以后的getView方法中使用?
如果是这样,我认为你应该尝试删除变量inflatergetView方法,创建一个本地inflaterLayoutInflater.from(parentView.getContext);
希望有所帮助。

+0

我绝对喜欢这个,并认为它已修复它,但我的泄漏必须是其他地方,因为它仍然是泄漏我会更新现在的问题与LeakCanary屏幕快照 – Rob85

+0

我已添加屏幕截图是否对您更有意义? – Rob85

+0

@ Rob85我更新了答案,请检查它是否有帮助。 – Minhtdh

0

好吧,所以我已经找到了问题,但我不明白,所以也许有些人可以评论和解释或回答为什么它这样做。该泄漏发生在聊天活动中。去聊天活动我在以前的活动按钮:

ChatButton.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View arg0) 
     { 
      Intent intent = new Intent(mContext, Chat.class); 
      mContext.startActivity(intent); 
     } 
    }); 

当我从

mContext.startActivity(intent) 

开始,我开始它的活动如果我改变了,只是

startActivity(intent); 

它不泄漏。

编辑

它仍然泄漏