ArrayAdapter unable to update contents

后端 未结 1 1671
[愿得一人]
[愿得一人] 2021-01-16 11:16

I am trying to update the contents of my ArrayAdapter. I have tried calling the method notifyDataSetChanged() on the adapter and invalidate() on th

相关标签:
1条回答
  • 2021-01-16 11:43

    Sir;

    check this out private ChannelRow[] channelData; that's your instance variable, you instantiate it in your onCreate() this way

    channelData = new ChannelRow[]{ // default data
        new ChannelRow("user1", "channel1"),
        new ChannelRow("user2", "channel2")
    }; // channelData is holding is reference to the object being created with the `new` keyword
    

    so for example if you add one more object to channelData and call your notifyDataSetChanged() it will refresh but in your createSessionsList(ArrayList<ParseObject> objects) method you assign your channelData to a new object like this channelData = channels.toArray(new ChannelRow[channels.size()]); and this reference is not what the ListView's Adapter data is pointing to, so your notifyDataSetChanged() does not work because it has not changed. what you have to do is recall the instantiation line, this is the complete code

    private void createSessionsList(ArrayList<ParseObject> objects){
    ArrayList<ChannelRow> channels = new ArrayList<>();
    ChannelRow newRow = null;
    
    for (ParseObject o : objects){
        newRow = new ChannelRow((String)o.get("hostName"), (String)o.get("chatTitle"));
        channels.add(newRow);
    }
    
    channelData = channels.toArray(new ChannelRow[channels.size()]);
    adapter = new ChannelAdapter(this, R.layout.channel_row, channelData);
    //edit started here   
    // set your Listview to the adapter    
    channelListView.setAdapter(adapter); // you set your list to the new adapter
    adapter.notifyDataSetChanged();// you can remove it if you like
    }
    

    EDIT 1

    if you hate the idea of calling this line adapter = new ChannelAdapter(this, R.layout.channel_row, channelData); all the time i'd suggest you use ArrayList and use the ArrayList.add(Object o) function to update your item then you can all notifyDataSetChanged() ..

    Hope it helps..

    0 讨论(0)
提交回复
热议问题