2013-05-07 174 views
0

我正在嘗試創建一個異步任務來處理一大堆數據庫條目,然後讓用戶知道該條目是使用附加到自身的textView製作的。我知道我無法觸及doInBackground中的視圖,但我無法使用任何其他方法工作。任何人都可以向我解釋如何讓我的代碼在AsyncTask中工作嗎?無法讓AsyncTask正常工作

代碼:

private class DBADDITION extends AsyncTask<Object, Void, Object> { 

     @Override 
     protected String doInBackground(Object... params) { 
      DBAdapter my_database = new DBAdapter(getApplicationContext()); 
      logout.append("\n" + "Start" + " "); 
      my_database.open(); 
      String temp = input.getText().toString(); 

      int i = Integer.parseInt(temp); 
      for (int j = 1; j <= i; j++) { 
       db.createEntry("example", 10 + j); 
       logout.setText("\n" + j + logout.getText()); 

      } 
      db.close(); 
      return "it worked"; 
     } 

     protected void onProgressUpdate(Integer... progress) { 

     } 

    } 
+0

您應該只返回 「它的工作」在所有工作實際完成時在'onPostExecute'方法中。 – hwrdprkns 2013-05-07 07:09:16

+0

更新ui應該在ui線程上使用runonuithread或處理程序完成或更新ui onPostExecute() – Raghunandan 2013-05-07 07:10:28

+0

當我嘗試返回「void」時,它不允許我這樣做。 – EGHDK 2013-05-07 07:11:21

回答

0
logout.setText() 

不能對UI從不同的線程中執行操作。所有UI操作都必須在UI線程上執行。由於logout是TextView對象,因此它不能直接從doInBackground方法觸摸它,因爲它運行在不同的線程上。你應該使用一個Handler實例,或者你有一個參考你的活動,你應該打電話runOnUiThreadrunOnUiThread允許您在UI Thread的活套管理器隊列上發佈Runnable,而不需要實例化處理程序。

final int finalJ = j; 
runOnUiThread(new Runnable() { 
     public void run() { 
     logout.setText("\n" + finalJ + logout.getText()); 
     } 
}); 


runOnUiThread(new Runnable() { 
     public void run() { 
     logout.append("\n" + "Start" + " "); 
     } 
}); 
+0

是的,註銷是一個textView。 – EGHDK 2013-05-07 07:11:53

+0

你應該使用Handler或者runOnUiThread方法 – Blackbelt 2013-05-07 07:12:26

+0

什麼是runOnUiThread方法? – EGHDK 2013-05-07 07:13:24

0

您需要覆蓋onPostExecute()方法。這會在doInBackground()方法後自動調用。這也是在UI線程上,因此你可以在這裏修改你的textView。

如果需要在doInBackground()之前執行一些UI更新,則覆蓋onPreExecute()方法。

此外,從您的doInBackground()刪除任何UI元素更新用的情況下,像setText()

0

您使用Activity.runOnUIThread()來的setText,像這樣的:

private class DBADDITION extends AsyncTask<Object, Void, Object> { 

    @Override 
    protected String doInBackground(Object... params) { 
     DBAdapter my_database = new DBAdapter(getApplicationContext()); 
     logout.append("\n" + "Start" + " "); 
     my_database.open(); 


     final String temp = input.getText().toString(); 
     int i = Integer.parseInt(temp); 
     for (int j = 1; j <= i; j++) { 
      db.createEntry("example", 10 + j); 
      youractivity.this.runOnUiThread(new Runnable() { 
       public void run() { 
        logout.setText("\n" + j + logout.getText()); 
       } 
     ); 

     } 
     db.close(); 
     return "it worked"; 
    } 

    protected void onProgressUpdate(Integer... progress) { 

    } 

}