tags:

views:

30

answers:

1

I read the Avoiding Memory Leaks article with interest, and am concerned about danging references to the context object. I have a class like the following.

public class MessageAdapter extends ArrayAdapter<Message> {

    private ArrayList<Message> items;
    private LayoutInflater inflater;
    public MessageAdapter(Context context, int textViewResourceId, ArrayList<Message> items) {
        super(context, textViewResourceId, items);
        this.items = items;
        inflater = LayoutInflater.from(context);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
            View v = convertView;
            if (v == null) {
                v = inflater.inflate(R.layout.message_row, null);
            }
            Message o = items.get(position);
            if (o != null) {
                TextView content = (TextView) v.findViewById(R.id.content);
                TextView date = (TextView) v.findViewById(R.id.date);
                content.setText(Html.fromHtml("<b>" + o.getSender() + "</b>: " + o.getContent().replace("\n", "<br/>")));
                date.setText(o.getReceived().toString());
            }
            return v;
    }
}

Is it a problem to have a reference to a LayoutInflater object, since it must be using the context object somehow? Is there a better design pattern for what I'm trying to do here? (Use the context only to initially inflate the XML; from then on just use the View that's passed in to getView)

+1  A: 

Your inflater is not static and your adapter and your activity will be destroyed in the same time. Normally your context is the activity so I don't see any problem if you don't keep references on your adapter elsewhere than setListAdapter.

fedj