0

我正在尝试创建一个异步任务来处理一大堆数据库条目,然后让用户知道该条目是使用附加到自身的 textView 创建的。我知道我无法触摸 内部的视图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) {

        }

    }
4

3 回答 3

0
logout.setText()

您不能从不同的线程对 UI 执行操作。所有的 UI 操作都必须在 UI 线程上执行。由于logout是一个 TextView 对象,因此您不能直接从 doInBackground 方法中触摸它,因为它在不同的线程上运行。你应该使用一个Handler实例,或者你有一个对你的活动的引用,你应该调用runOnUiThread. runOnUiThread允许您Runnable在 的 looper 队列上发布一个UI Thread,而无需实例化一个 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" + " ");
       }
 });
于 2013-05-07T07:11:32.213 回答
0

您需要覆盖该onPostExecute()方法。这是在doInBackground()方法之后自动调用的。这也是在 UI 线程上,因此您可以在此处修改您的 textView。

万一,您需要在 doInBackground() 之前执行一些 UI 更新,然后覆盖该onPreExecute()方法。

doInBackground()此外,从您的喜欢中删除任何 UI 元素更新的实例setText()

于 2013-05-07T07:11:40.557 回答
0

您使用 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) {

    }

}
于 2013-05-07T07:13:46.733 回答