2016-05-23 58 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 
     } 
    } 
}