2013-01-20 15 views
-1

我有一個主要活動,我創建一個適用於arraylist數據的適配器。 我使用Jsoup的單獨線程從網站上讀取新聞。Android:從適配器和活動共享數據

在的onCreate()我有

this.newsItemAdapter = new NewsItemAdapter(this, 
         R.layout.newsitem_row,NewsItemAdapter.getAllNews()); 
parseThread.start(); 
this.newsItemAdapter.notifyDataSetChanged(); 

當我從適配器讀取,我得到空單。這是因爲線程尚未完成。任何想法,我應該如何繼續?

我不能在我的線程中執行notifyDataSetChanged,因爲它不是適配器的所有者。

回答

0

你需要單獨的線程完成後通知,並在UI線程調用notifyDataSet,一種可能的方法是使用處理器,

可以定義活動的處理程序,調用中的handleMessage notifyDataSet變化,如

handler = new android.os.Handler() { 
     @Override 
     public void handleMessage(Message msg) { 
      newsItemAdapter.notifyDataSetChanged(); 
     } 
} 

,並在線程的run方法,你需要發送一個消息處理程序,

public void run() { 
    // add this to the end 
    Message msg = new Message() 
    handler.sendMessage(msg); 
} 

否則,你可以使用的AsyncTask instea獨立線程的d,在任務的doInBackground方法中使用jsoup,並在onPostExecute中使用notifyDataSet。

處理程序文檔是http://developer.android.com/reference/android/os/Handler.html,而AsyncTask的是http://developer.android.com/reference/android/os/AsyncTask.html

0

將適配器傳遞給您的線程在其構造函數中。然後你的線程可以調用notifyDataSetChanged。

+0

嗨,對不起,似乎似乎沒有工作,即使你將適配器傳遞給該線程,它仍然不屬於(如在內部未創建)線程。 –