Android 线程更新UI报错 : Can't create handler inside thread that has not called Looper.prepare()

时间:2023-02-14 20:42:15

MainActivity中有一个按钮,绑定了save方法

public void save(View view) {
String title
= titleText.getText().toString();
String timelength
= lengthText.getText().toString();

ExecutorService exec
= Executors.newCachedThreadPool();
exec.execute(
new NewsService(getApplicationContext(),title,timelength));
}

NewsService代码:

@Override
public void run() {
String path
= "http://192.168.0.102:8080/videonews/ManageServlet";
Map
<String,String> params = new HashMap<String,String>();
params.put(
"title",title);
params.put(
"timelength",timelength);
boolean result=false;
try {
result
= sendGETRequest(path,params);
}
catch (Exception e) {
e.printStackTrace();
}

if(result) {
Toast.makeText(context, R.string.success, Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(context,R.string.error,Toast.LENGTH_LONG).show();
}
}

报错:

04-18 13:06:36.191    2284-2305/test.example.com.newsmanage E/AndroidRuntime﹕ FATAL EXCEPTION: pool-1-thread-1
Process: test.example.com.newsmanage, PID:
2284
java.lang.RuntimeException: Can
't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.
<init>(Handler.java:114)
at android.widget.Toast$TN.
<init>(Toast.java:336)
at android.widget.Toast.
<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:
250)
at android.widget.Toast.makeText(Toast.java:
277)
at test.example.com.service.NewsService.run(NewsService.java:
86)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:
1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:
587)
at java.lang.Thread.run(Thread.java:
818)

查了资料,说是Android中不能在子线程中来刷新UI。如果要实现你这功能的话。建议是在你的子线程中添加hander来发送消息更新线程。

下面这样做就OK了

1.在Activity中增加如下代码

private Handler myHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 0x00 :
Toast.makeText(getApplicationContext(),
"save success",Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(getApplicationContext(),
"save fail",Toast.LENGTH_SHORT).show();
}

}
};

2.启动线程时,将handler传入:

exec.execute(new NewsService(getApplicationContext(),myHandler,title,timelength));

3.在线程中,发送消息给handler:

@Override
public void run() {
String path
= "http://192.168.0.102:8080/videonews/ManageServlet";
Map
<String,String> params = new HashMap<String,String>();
params.put(
"title",title);
params.put(
"timelength",timelength);
boolean result=false;
try {
result
= sendGETRequest(path,params);
}
catch (Exception e) {
e.printStackTrace();
}
Message msg
= new Message();
if(result)
msg.what
= 0x00;
else
msg.what
= 0x01;
handler.sendMessage(msg);
}

完成。