簡體   English   中英

無法使AsyncTask工作

[英]Can't get AsyncTask to work

我正在嘗試創建一個異步任務來處理一大堆數據庫條目,然后讓用戶知道該條目是使用附加到其自身的textView進行的。 我了解我無法觸摸doInBackground內部的doInBackground ,但是無法使用任何其他方法。 誰能向我解釋如何使我的代碼在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) {

        }

    }
logout.setText()

您無法通過其他線程在UI上執行操作。 所有UI操作都必須在UI線程上執行。 由於logout是TextView對象,因此您無法直接通過doInBackground方法觸摸它,因為logout在另一個Thread上運行。 您應該使用Handler實例,或者,如果您有對Activity的引用,則應該調用runOnUiThread runOnUiThread允許您在UI Thread runOnUiThread器隊列上發布Runnable ,而無需實例化Handler。

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" + " ");
       }
 });

您需要重寫onPostExecute()方法。 這是在doInBackground()方法之后自動調用的。 這也位於UI線程上,因此您可以在此處修改textView。

如果發生這種情況,您需要在doInBackground()之前執行一些UI更新,然后覆蓋onPreExecute()方法。

另外,從doInBackground()刪除任何UI元素更新的實例,例如setText()

您可以使用Activity.runOnUIThread()來設置文本,如下所示:

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) {

    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM