Androiderson
Androiderson

Reputation: 17083

ListView gets updated without calling notifyDataSetChanged

I would like to know why do I get a list with the sixth item if I'm telling my adapter to work with only 5 items and I don't call notifyDataSetChanged.

    public class MainActivity extends Activity {

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            final ListView list = (ListView) findViewById(R.id.list);
            final List<Integer> data = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4, 5));
            list.setAdapter(new MyAdapter(data));
            data.add(6);
        }

        class MyAdapter extends BaseAdapter {
            List<Integer> data;

            public MyAdapter(List<Integer> _data) {
                data = _data;
            }

            @Override
            public int getCount() {
                return data.size();
            }

            @Override
            public Object getItem(int i) {
                return data.get(i);
            }

            @Override
            public long getItemId(int i) {
                return data.get(i);
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                TextView textView = new TextView(MainActivity.this);
                textView.setText(String.valueOf(data.get(i)));
                return textView;
            }
        }
    }

Upvotes: 0

Views: 59

Answers (1)

laalto
laalto

Reputation: 152917

setAdapter() doesn't synchronously refresh the ListView but just posts a message to the main UI thread queue that the layout needs to be refreshed. When the ListView does its layout/draw pass, its adapter in fact has 6 items you've added in your main UI thread before returning control to the main thread looper that processes the message queue.

Upvotes: 3

Related Questions