2010-05-26 97 views
0

我已經創建了一個自定義列表視圖,它看起來是Twitter的時間表,幷包含帖子。以下函數從服務器獲取帖子列表,解析它們並將它們添加到用於填充列表視圖的列表中。ListView沒有得到更新調用notifyDataSetChanged()

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(); 
    } 

調用該函數後,列表適配器在數據集中在主線程中調用

adapter.notifyDataSetChanged(); 

通知的變化。但是,該列表視圖不會更新。爲了追蹤目的,我在列表視圖頂部添加了一個按鈕, 再次調用populateTimeline(),然後在點擊按鈕時調用notifyDataSetChanged()。令人驚訝的是,這次在ListView中彈出所有帖子。

應該怎麼做才能更新列表視圖沒有按鈕點擊?

回答

1

我正在使用Gson來解析Json,並且花了太長時間來解析json數組並填充了導致adapter.notifyDataSetChanged被調用的列表,甚至在調用之前有任何更改列表。所以我將notifyDataSetChanged轉換爲函數,並在延遲(Thread.sleep())後調用它來解決問題。

0

adapter.notifyDataSetChanged();應該在UI /主線程上調用

+0

它正在主線程中調用。 – primpap 2010-05-26 15:26:09

+0

你如何在主線程上調用它? – 2010-08-30 22:37:33

+0

你可以通過使用這裏描述的Handler類來實現:http://www.vogella.de/articles/AndroidPerformance/article.html – 2011-10-06 16:25:57

相關問題