是android的新手..我试图在android中实现线程。但我得到错误..我google搜索并获得答案“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();
答案 0 :(得分: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();
答案 1 :(得分:0)
好像你需要在MainActivity中创建处理程序然后再进一步传递它。像这样:
private Handler handler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
}