0

我是 android 的新手 .. 正在尝试在 android 中实现线程。但是出现错误..我用谷歌搜索并得到答案“AsyncTask”,但我真的不知道如何实现

错误信息

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

我的代码

final Thread thread = new Thread(){
                        @Override
                            public void run() {
                            try {
                                DatabaseHandler dbh = new DatabaseHandler(test.this);
                                result=dbh.Verify(1);
                                if(result != ""){

                                    getData();
                                    progress.dismiss();

                                }
                                else{


                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    };
                    thread.start();
4

2 回答 2

0

使用以下代码在 UI 线程中运行。

Runnable runnable = new Runnable() {
            @Override
            public void run() {
                handler.post(new Runnable() { // This thread runs in the UI
                    @Override
                    public void run() {
                       DatabaseHandler dbh = new DatabaseHandler(test.this);
                            result=dbh.Verify(1);
                            if(result != ""){

                            getData();
                            progress.dismiss();

                        }
                        else{


                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    };
    new Thread(runnable).start();
于 2013-04-27T06:15:49.527 回答
0

似乎您需要在 MainActivity 中创建处理程序,然后进一步传递它。像这样:

private Handler handler;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    handler = new Handler();
}
于 2013-04-27T06:26:24.200 回答