views:

261

answers:

2

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 jsonString = 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?

A: 

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

Alex Volovoy
It is being called in the main thread.
primalpop
how do you call it on the main thread?
Sheehan Alam
A: 

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.

primalpop