2016-05-23 98 views
0

我正在編寫一個Android應用程序,它從SQLite Database中讀取數據,然後在下一個屏幕上顯示數據。每當我對數據庫進行查詢時,都會收到一條錯誤消息,說明主線程正在做太多的工作。Android其他線程和Looper

然後我把我的查詢在一個新的主題:

 (new Thread() 
     { 
      public void run() 
      { 
       Looper.prepare(); 
       try 
       { 
        FPJobCardWizard data = dbHelperInstance.loadFPJobCardWizardFull(fitmentHash); 
        wState.fitmentItemSet(data.fitmentItemGet()); 
       } catch (Exception e) {e.printStackTrace();} 
       Looper.loop(); 
      } 
     }).start(); 

現在的GUI /主線程完成它之前的查詢中完整的操作和結果的data變量仍然是空的。我閱讀了幾篇文章和API文檔,似乎我需要使用Looper(這似乎是正確的修復),但我從來沒有使用Looper,似乎無法使其工作。

請你可以檢查上面的代碼,並指引我在正確的方向。

謝謝大家提前。

AsyncTask life cycle

+0

使用處理程序將數據發送到UI線程。 –

回答

0

的最佳選擇,這裏將被使用AsyncTask,因爲它會允許你在後臺線程中執行所有的後臺工作,那麼就不會產生結果時,它會使用UI線程應用它

因此,如在AsyncTask生命週期的解釋,你可以做所有的方法doInBackground()你的工作背景,然後做你的用戶界面的工作將在其從doInBackground()方法採用結果後執行的方法onPostExecute()根據生命週期,並將你的手放在上,看看this example它提供了以下示例代碼:

public class AsyncTaskTestActivity extends Activity { 

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

     // This starts the AsyncTask 
     // Doesn't need to be in onCreate() 
     new MyTask().execute("my string paramater"); 
    } 

    // Here is the AsyncTask class: 
    // 
    // AsyncTask<Params, Progress, Result>. 
    // Params – the type (Object/primitive) you pass to the AsyncTask from .execute() 
    // Progress – the type that gets passed to onProgressUpdate() 
    // Result – the type returns from doInBackground() 
    // Any of them can be String, Integer, Void, etc. 

    private class MyTask extends AsyncTask<String, Integer, String> { 

     // Runs in UI before background thread is called 
     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 

      // Do something like display a progress bar 
     } 

     // This is run in a background thread 
     @Override 
     protected String doInBackground(String... params) { 
      // get the string from params, which is an array 
      String myString = params[0]; 

      // Do something that takes a long time, for example: 
      for (int i = 0; i <= 100; i++) { 

       // Do things 

       // Call this to update your progress 
       publishProgress(i); 
      } 

      return "this string is passed to onPostExecute"; 
     } 

     // This is called from background thread but runs in UI 
     @Override 
     protected void onProgressUpdate(Integer... values) { 
      super.onProgressUpdate(values); 

      // Do things like update the progress bar 
     } 

     // This runs in UI when background thread finishes 
     @Override 
     protected void onPostExecute(String result) { 
      super.onPostExecute(result); 

      // Do things like hide the progress bar or change a TextView 
     } 
    } 
}