开发者

Implementation ListAdapter and possible memory leaks

开发者 https://www.devze.com 2023-02-13 10:59 出处:网络
I have a very simple Activity: public class A extends ListActivity implements ListAdapter { @Override public void onCreate(Bundle b)

I have a very simple Activity:

public class A extends ListActivity implements ListAdapter
{
    @Override public void onCreate(Bundle b)
    {
        super.onCreate(b);
        setListAdapter(this); //no problems without this line
    }
    // etc... (empty implementation ListAdapter interface functions)
}

When I start this Activity from other activity:

startActivity(new Intent(this, A.class));

and bush "back" button (to destroy this activity), the heap grows up about 13..15 kbytes and doesn't reduce back even after GC works out.

When I start and finish this activity again, the head grows up more and more.

To monitor the heap size I use DD开发者_开发百科MS in Eclipse.

What am I doing wrong?


I would really urge you not to implement ListAdapter in the same class as your Activity. Its not a good programming practice and all the Android tutorials create separate classes as adapters. They certainly do not merge the adapter and activity into one class. For example consider the GridView tutorial as an example of my point.

The problem lies where you say setListAdapter(this) in my opinion. "this" refers to the ListActivity class A, which is not an adapter by any means. for the correct use of setListAdapter you should pass either an ArrayAdapter or create your own Adapter class (which implements ListAdapter, and extend BaseAdapter) and instantiate it.

I think this may solve your problem, as your setting the adapter of the view to the activity itself, which seems recursive or a kind of "infinite loop" in some nature.


Do you cache views inside getView() method of ListAdapter implementation? If the answer is yes then caching may be a reason of memory leaks. For example leaks can happen because of using static members or View.setTag(int, Object) for storing views.

Anyway I recommend you to install MAT Plugin, start and finish this activity for 5-10 times and analyze heap. After that you'll be able to see leaked objects and root of leaked object hierarchies.

0

精彩评论

暂无评论...
验证码 换一张
取 消