Android 线程更新UI报错 : Can't create handler inside thread that has not called Looper.prepare()
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);
    }
完成。
Android 线程更新UI报错 : Can't create handler inside thread that has not called Looper.prepare()的更多相关文章
- 关于子线程使用Toast报错Can't create handler inside thread that has not called Looper.prepare()的解决办法
		形同如下代码,在Thread中调用Toast显示错误信息: new Thread(new Runnable(){ @Override public void run() { try{ weatherD ... 
- 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()
		在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException: Can't create handler inside thread that has ... 
- 【转】在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()
		在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException: Can't create handler inside thread that has ... 
- 转 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()
		在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException: Can't create handler inside thread that has ... 
- 工具类ToastUtil  避免在子线程中使用抛异常 "Can't create handler inside thread that has not called Looper.prepare()"
		package com.example.kbr.utils; import android.view.Gravity; import android.widget.Toast; import io.r ... 
- Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()
		问题: 写了一个sdk给其他人用,提供一个回调函数,函数使用了handler处理消息 // handler监听网络请求,完成后操作回调函数 final Handler trigerGfHandler ... 
- Android进阶(十六)子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误
		原子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误 今天用子线程调Toast报 ... 
- OkHttp下载文件中途断网报Can't create handler inside thread that has not called Looper.prepare()异常的解决办法
		最近做项目时出现个问题. 在一个基类中,创建一个Handler对象用于主线程向子线程发送数据,代码如下: this.mThirdHandler = new Handler(){ @Override p ... 
- Android进阶(八)Can't create handler inside thread that has not called Looper.prepare()
		Error:Can't create handler inside thread that has not called Looper.prepare() 原代码: //利用Handler消息传递机制 ... 
随机推荐
- java抓取快递100信息接口
			package zeze; import java.io.IOException; import org.json.JSONArray; import org.json.JSONException; ... 
- 转:sql之left join、right join、inner join的区别
			left join(左联接) 返回包括左表中的所有记录和右表中联结字段相等的记录 right join(右联接) 返回包括右表中的所有记录和左表中联结字段相等的记录inner join(等值连接) 只 ... 
- 获取shell脚本自身所在目录的Shell脚本分享
			前几天写的七牛的参赛demo,用bash写了一个便捷安装的脚本,涉及到了路径相关的判断,从stackoverflow,加上自己的实践整理一下. 简单版 下面是一个最简单的实现,可以解决大多数问题,缺陷 ... 
- js判断checkbox状态,处理表单提交事件
			功能描述:手机网页需要一个投票功能,通过form的post提交.有5-20个checkbox选项,至少选一项,至多选三项.需要在用户点击提交按钮前,判断checkbox的状态是否符合条件,符合则提交到 ... 
- ModelState.IsValid
			model内的设置如下所示: /// <summary> /// 取得或设置邮编 /// </summary> [RegularExpression(@"(^[1-9 ... 
- C#之Textbox实现自动提示容、自动补齐内容
			今发现一个博文挺有意思,实现的功能很有意思但方法却很简单,特此转过来,以备以后查阅. 先上原博文地址:http://blog.csdn.net/testcs_dn/article/details/45 ... 
- Qt QThread 多线程使用
			一.继承QThread 使用方法 1.创建个继承QThread的类. #ifndef MYTHREAD_H #define MYTHREAD_H #include <QObject> #i ... 
- FFmpeg-20160428-snapshot-bin
			ESC 退出 0 进度条开关 1 屏幕原始大小 2 屏幕1/2大小 3 屏幕1/3大小 4 屏幕1/4大小 S 下一帧 [ -2秒 ] +2秒 ; -1秒 ' +1秒 下一个帧 -> -5秒 F ... 
- Django~Views
			In Django, web pages and other content are delivered by views. To get from a URL to a view, Django u ... 
- LAMP 之 mysql 安装
			搞了成日 = = 呢个野.... 大部分东西写在 印象笔记 中....不过呢个野特别繁琐,所以记录落黎(小白一枚,大家见谅) 总结下,唔系好容易唔记得 >W< (可能唔会甘完整,我将我自认 ... 
