开发者

ListView not getting updated on calling notifyDataSetChanged()

I've created a custom listview which looks the twitter timeline and contains posts. The following function gets a list of posts from server, parses them and adds them to the list used to populate the listview.

public void populateTimeline(){
        Thread populate = new Thread(){
            public void run(){
                Looper.prepare();
                InputStream data = getData(serviceURL);  //gets a jsonarray of posts from server  $ post_list
                if(data!= null)
                    try {

                            String jsonStrin开发者_开发技巧g = responsetoString(data);
                            Log.d(TAG, jsonString);
                            PostList list = getPostList(jsonString);
                            List <PostContainer> post_list = list.getPostContainterList(); 
                            PostContainer pc;
                            for (int i = 0; i < post_list.size(); i++) {            
                                pc = post_list.get(i);
                                mObjectList.add(pc.getPost()); //Adding each post to the list
                                Log.d(TAG, pc.post.username);
                                Log.d(TAG, pc.post.message);
                            }

                    } catch (Exception e) {
                        Log.d(TAG, "Exception" + e.getMessage());
                        e.printStackTrace();
                    }
                Looper.loop();              
            }

        };
        populate.start();
    }

After calling this function, the list adapter was notified of change in data set by calling

adapter.notifyDataSetChanged();

in the main thread. But the listview doesn't updated. For trail purpose I added a button on top of list view and called the populateTimeline() again and then notifyDataSetChanged() when the button was clicked. Surprisingly all the posts pop up in the ListView this time.

What should be done so as to update the listview without the button click?


I was using Gson to parse Json and was taking a little too long to parse the json array and populate the list which resulted in adapter.notifyDataSetChanged being called even before there was any change in the list. So I shifted notifyDataSetChanged to a function and called it after a delay (Thread.sleep()) which solved the problem.


adapter.notifyDataSetChanged(); should be called on UI/Main thread

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜