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()的更多相关文章

  1. 关于子线程使用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 ...

  2. 在子线程中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 ...

  3. 【转】在子线程中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 ...

  4. 转 在子线程中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 ...

  5. 工具类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 ...

  6. Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()

    问题: 写了一个sdk给其他人用,提供一个回调函数,函数使用了handler处理消息 // handler监听网络请求,完成后操作回调函数 final Handler trigerGfHandler ...

  7. 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报 ...

  8. OkHttp下载文件中途断网报Can't create handler inside thread that has not called Looper.prepare()异常的解决办法

    最近做项目时出现个问题. 在一个基类中,创建一个Handler对象用于主线程向子线程发送数据,代码如下: this.mThirdHandler = new Handler(){ @Override p ...

  9. 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消息传递机制 ...

随机推荐

  1. ubuntu14 谷歌输入法

    sudo apt-get install ibus-googlepinyin 装完重启即可: (在右上角语言处右键,添加text entry)

  2. ffmpeg解码音频流

    //初始化.注册编解码器 avcodec_init(); av_register_all(); avformat_network_init(); //选取测试文件 char* FileName=&qu ...

  3. Nunit-Writing Tests

    Nunit 测试可以被任意支持attributes的.net语言使用 Attributes被用于去标识测试类和测试方法,然后通过不同的方式修改他们的行为 Assertions针对一个或多个约束,测试一 ...

  4. 【leetcode】Excel Sheet Column Title

    Excel Sheet Column Title Given a non-zero positive integer, return its corresponding column title as ...

  5. POJ 2769

    http://poj.org/problem?id=2796 题意:求n个数的和乘以这n个数中的最小值的积最大的数,以及其范围. 思路:求每一个数两边的比其大的数的和,再乘以这个数.还有一个范围,用单 ...

  6. pip安装简单方法

    前提:有网络 wget -c --no-check-certificate https://bootstrap.pypa.io/get-pip.py python get-pip.py

  7. wxpython 基本的控件 (文本)

    wxPython 工具包提供了多种不同的窗口部件,包括了本章所提到的基本控件.我们涉及静态文本.可编辑的文本.按钮.微调.滑块.复选框.单选按钮.选择器.列表框.组合框和标尺.对于每种窗口部件,我们将 ...

  8. cocos2dx旧版本支持arm64修改

    修改的版本是cocos2dx.2.2 1.在neon_matrix_impl.c中修改 #if defined(__ARM_NEON__)为 #if defined(_ARM_ARCH_7) 2.在m ...

  9. 欧洲杯 2016 高清直播 - 观看工具 UEFA-EURO-2016-Play.7z

    OnlineTV-MPlayer-nocache.exe 占 CPU 内存 较少 OnlineTV-FFPlay.exe 可截取图像 UEFA-EURO-2016-Play-v5.7z UEFA-EU ...

  10. AUTOSSH,ssh反向代理

    在本地机器   1)ssh-keygen   2)ls ~/.ssh/   应该有三个文件 id_rsa id_rsa.pub known_hosts   拷贝id_rsa.pub到远程服务器,然后在 ...