Can't find the leak, on my fragment android code

青春壹個敷衍的年華 提交于 2019-12-11 12:14:18

问题


I have a TabLayout, under each tab there is a Fragment (I'm using ArrayPagerAdapter). I've noticed that when I switch many times from a tab to another, my memory usage increase a lot. From my heap snapshot, I can see there are a lot of AutoCompleteTextView instances.

So I am convinced that the problem could be here:

public class MyFragment  {
...
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    ...
    final MultiAutoCompleteTextView eInput = (MultiAutoCompleteTextView) v.findViewById(R.id.TextInput);
    EditorListener mEditorListener = new EditorListener();
    eInput.setOnEditorActionListener(mEditorListener);
    eInput.addTextChangedListener(new WhitespaceWatcher());
    eInput.setAdapter(mDictionaryAdapter);
    eInput.setTokenizer(new SpaceTokenizer());
    ...
  }
...
  class EditorListener implements TextView.OnEditorActionListener
  {
  @Override
  public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
    ...
    MultiAutoCompleteTextView input = (MultiAutoCompleteTextView) textView.findViewById(R.id.TextInput);
    ...
  }
}
...
}

But I can't understand where exactly the problem is.


回答1:


Note to others: the poster and I had an off-SO discussion about this issue, and the poster created this sample app that was able to reproduce the problem.


After some struggling, I was able to get LeakCanary to work. It required 1.4-beta1 versus the shipping 1.3.1. All I needed to do was add the dependencies and set up an Application subclass per the LeakCanary docs. Then, launch the app and press BACK once the activity appears.

You get:

Whether this is a framework bug or something introduced by appcompat-v7 and its specific subclass of MultiAutoCompleteTextView, I can't say at present. However, it is definitely not a bug in your code.

Clearing the adapter from the MultiAutoCompleteTextView (setAdapter(null)) in onDestroyView() of the fragment should prevent it from leaking the activity, but the widget itself will still leak. A quick scan of the relevant code does not give me much hope that the leak itself can be fixed without modifications to either the framework (for MultiAutoCompleteTextView) or appcompat-v7 (for its subclass).



来源:https://stackoverflow.com/questions/35153410/cant-find-the-leak-on-my-fragment-android-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!