2014-01-30 27 views
1

我有一個名爲BuildingActivity的活動,它擴展了ListActivityAndroid - 從後臺線程返回ArrayList到活動

onCreate()方法中,我在後臺線程中運行7個數據庫查詢。在後臺線程中,我正在從查詢返回的數據構建一個ArrayList<String>對象。

現在,我想返回ArrayList<String>對象返回到我的BuildingActivity線程。

這裏,即時通訊工作的部分代碼:

public class BuildingActivity extends ListActivity { 

     private ProgressBar mProgressBar; 

     public ArrayList<String> buildings; 

     @Override 
     public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_building); 

      new Thread(new Runnable() { 

       @Override 
       public void run() { 
        ArrayList<String> list; 

        DataSource dbSource = new DataSource(getApplicationContext()); 
        dbSource.open(); 

        list = dbSource.getBuildingsList(); 

        dbSource.close(); 

        //*** NOW HOW DO I PASS list BACK TO onCreate()? 
        //*** I WANT TO MAKE buildings = list. 

       } 

      }).start(); 

      if(!buildings.isEmpty()) { 
      // do Something. 
      // If i do buildings = list in the background thread, 
      // This will always be executed because the background thread can take 
      // some time to return the data. How do i make sure this part of 
      // code is executed only after the data has been returned? 
     } 
     } 
    } 

我的目標後,這是創建一個列表,從這個返回大廈名單。而在點擊建築物時,另一項活動將開放。我如何解決這個問題?

謝謝!

+0

看下面的方法....當你的列表不是null,那麼你可以添加一個條件/ /在這裏返回你的列表塊到UI線程 –

+0

isnt buildings = list possible?錯誤是什麼? –

+0

@ Rat-a-tat-a-tat料理鼠王有可能。但是隨後線程下面的'if'語句將一直執行,因爲Activity線程不會等待後臺線程完成。 –

回答

1

如何確保只有在返回數據 後才能執行這部分代碼?

而不是使用線程在後臺使用AsyncTask做任務,這對於在後臺執行操作提供doInBackgroundonPostExecute方法來完成後臺任務

+0

是的。我讀過關於AsyncTask的內容。我甚至通過嵌套一個在我的BuildingActivity中擴展AsyncTask的類來嘗試這種方法。但是我無法從onPostExecute()方法訪問BuildingActivity的buildings數據成員。 –

+0

@AninditKarmakar:創建一個擴展AsyncTask並在全局onPostExecute中聲明所有想要訪問的成員的BuildingActivity內部類。請分享AsyncTask相關代碼以獲得更多幫助 –

0

這裏經過的UI線程上運行使用此

public void myMethod(){ 
    Thread background = new Thread(new Runnable(){ 
     @Override 
     public void run(){ 
      Looper.prepare(); 
      //Do your data rerieval work here 
       Runnable r=new Runnable() { 
       @Override 
       public void run() { 
        //return your list from here      
       } 
      }; 
      handler.post(r); 
      Looper.loop(); 
     } 
    }); 
    background.start(); 
}