简体   繁体   中英

ListView doesn't refresh on notifyDataSetChanged

ListView doesn't seem to refresh when notifyDataSetChanged(); is called, but does refresh when its adapter gets set again.

In my Activity onCreate I initialize my ListView and my adapter. Then I have this Hanler that checks for new values every second. listview.setAdapter(arrayAdapter); works but arrayAdapter.notifyDataSetChanged(); doesn't do anything.

Here is the code:

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

                     lv = (ListView) findViewById(R.id.listView1);

            arrayAdapter = new ArrayAdapter<Integer>(this,android.R.layout. simple_list_item_1, myIntegers);
            lv.setAdapter(arrayAdapter);
    }

    private Handler handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                if (msg.what == DIS){
                    handler.sendEmptyMessageDelayed(DIS, 1000);
                    if(!refresh()){
                        handler.removeMessages(DIS);
                    }
                }
            }
        };

   public boolean refresh(){

        if(ports.isEmpty()){
            return false;
        }else{
            listview.setAdapter(arrayAdapter); //WORKS
    arrayAdapter.notifyDataSetChanged(); // DOESN'T WORK
            return true;
            }
    }

So I was wondering how to make that work with notifyDataSetChanged , because I read that it is the right way to do it, and anyway even if the setAdapter does work it makes my listview jump to beginning every time it refreshes it.

EDIT:

To clarify things, I am adding more values to myIntegers.

Try instead adding the values using the adapter.add() method. I dont think you can modify the array that was used to create the adapter and then expect it to hold an updated instance to update the views from. Best of Luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM