no change/black screen by notifyDataSetChanged();

放肆的年华 提交于 2019-12-02 18:22:36

问题


I want to do something like this.

while pressing the refresh button, it will refresh the list. Activity codes are like this:

        adapter = new TweetAdapter(Welcome.this, tweets, users);
        tweetsList.setAdapter(adapter);


    private void refreshAdapter() {
        adapter.clear();
        adapter.refresh(tweets, users);
    }

refreshAdapter() called when I need to change the list item. here tweets & users are ArrayList & HashMap items

and the adapter part is like this:

public void clear() {
    this.tweets.clear();
    this.users.clear();
}

public void refresh(ArrayList<Tweet> tweets, HashMap<String, User> users) {
    this.tweets.addAll(tweets);
    this.users.putAll(users);
    Collections.sort(this.tweets, new TweetTimeComparator());
    notifyDataSetChanged();
}

but unfortunately notifyDataSetChanged(); is not working. by clicking refresh the list either turns black(maximum time) or have no response(some time).

please tell me if you find the error or suggest me what to do.


回答1:


I think you are clearing the data

this.tweets.clear();
this.users.clear();

.. I think as tweets and users both has same refreance ( as passed from activity to adapter ) so both tweets and both users (on adapter and on activity are pointing to same ArrayLists) so both are get-clear so these line not make sense as both are empty

this.tweets.addAll(tweets);
this.users.putAll(users);

try

public TweetAdapter(Context context, ArrayList<Tweet> tweets, HashMap<String, User> users) { 

mInflater = LayoutInflater.from(context); 
this.tweets = new ArrayList<Tweet>(); 
this.users = new HashMap<String, User>();

this.tweets.addAll(tweets);
this.users.putAll(users);

Collections.sort(this.tweets, new TweetTimeComparator()); 
} 

..

public void refresh(ArrayList<Tweet> tweets, HashMap<String, User> users) {

  this.tweets.clear();
    this.users.clear();

    this.tweets.addAll(tweets);
    this.users.putAll(users);
    Collections.sort(this.tweets, new TweetTimeComparator());
    notifyDataSetChanged();
}

but NOTE : now reference to both tweets (on adapter and on activity) and both users (on adapter and on activity) are different.

There should no direct assignment like adapter.tweets = activity.tweets any where other use this.tweets.addAll(tweets);



来源:https://stackoverflow.com/questions/11228698/no-change-black-screen-by-notifydatasetchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!