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()

时间: 2024-08-21 23:48:54

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

关于子线程使用Toast报错Can&#39;t create handler inside thread that has not called Looper.prepare()的解决办法

形同如下代码,在Thread中调用Toast显示错误信息: new Thread(new Runnable(){ @Override public void run() { try{ weatherData = getWeatherData(strUrl); parseJson(weatherData); }catch(Exception e){ Toast.makeText(WindowApplication.getAppContext(), e.toString(), Toast.LENGT

转 在子线程中new Handler报错--Can&#39;t create handler inside thread that has not called Looper.prepare()

在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has not called Looper.prepare()  这是因为Handler对象与其调用者在同一线程中,如果在Handler中设置了延时操作,则调用线程也会堵塞.每个Handler对象都会绑定一个Looper对象,每个Looper对象对应一个消息队列(MessageQueue).如果在创建Ha

Android蓝牙开发,报BluetoothAdapter﹕ Can&#39;t create handler inside thread that has not called Looper.prepare

这个错误翻译的意思是:不能在没有Looper.prepare的线程里面创建handler. 起初我很疑惑,我根本没有用到工作线程,也没有创建handler.报错的代码如下: // Device scan callback. private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() { @Override public void onLeScan(final Blu

Android handler 报错处理Can&#39;t create handler inside thread that has not called Looper.prepare()

解决方法,在ui线程里面创建handler m_MainActivity.runOnUiThread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub GameBoxUtil.startPay(m_MainActivity,String.valueOf(amount), productName, payCode,orderId,payHandler); }}); Android han

(android)Can&#39;t Create handler inside thread that has not called Looper.prepare()

接android游戏sdk中,经常会遇到Looper报错,此时需要在主线程中调用sdk函数. 将sdk的函数放到UI线程中执行. 如: activity.runOnUiThread(new Runnable() { @Override public void run() { } }); (android)Can't Create handler inside thread that has not called Looper.prepare()

Android : Can&#39;t create handler inside thread that has not called Looper.prepare()

又报错了,不过早也习以为常了. Can't create handler inside thread that has not called Looper.prepare() 我把文档给摘录下来了,大家可以看看. 这个类被用于为线程运行消息循环.默认线程并没有消息循环与之关联,所以你需要创建一个,在线程中调用prepare()以运行这个循环,然后调用loop()在循环结束时获取进程信息. 和消息循环交互最多的就是通过Handler类. 下面是一个实现了Looper线程的典型实例,通过分离的pre

使用okhttp 报Can&#39;t create handler inside thread that has not called Looper.prepare()

我是在用okhttp的请求数据,在处理数据的时候,打开了一个dialog用来提示,然后报了这个错误. 经过调试,发现错误原因是: dialog必须在一个被Looper.prepare()回调的的线程里创建,但是okhttp这个线程不具备这个条件 <span style="font-size:14px;">OkHttpUtil.getDataInGet(updateUrl, new Callback() { @Override public void onFailure(Re

Android Exception 13(Can&#39;t create handler inside thread that has not called Looper.prepare())

10-12 17:02:55.500: E/AndroidRuntime(28343): FATAL EXCEPTION: Timer-2 10-12 17:02:55.500: E/AndroidRuntime(28343): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 10-12 17:02:55.500: E/AndroidRuntim

Android java.lang.RuntimeException: Can&#39;t create handler inside thread that has not called Looper.prepare()

E/AndroidRuntime(7200): Uncaught handler: thread Thread-8 exiting due to uncaught exceptionE/AndroidRuntime( 7200): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 原因是非主线程中默认没有创建Looper对象,需要先调用Looper