首页 > 技术文章 > java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()解决办法

shmilyGWT 2017-12-22 22:10 原文

代码改变世界

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()解决办法

 

android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called

原因是在子线程弹Toast了, 切记,Toast只能在UI线程弹出

 

解决办法:

new Thread(new Runnable() {  
              
            @Override  
            public void run() {  
                // TODO Auto-generated method stub  
                  
                try {  
                    Thread.sleep(1000);  
                    handler.sendEmptyMessage(0);  
                } catch (InterruptedException e) {  
                    // TODO Auto-generated catch block  
                    e.printStackTrace();  
                }  
                  
            }  
        }).start();

  

private Handler handler = new Handler() {  
  
        @Override  
        public void handleMessage(Message msg) {
      Toast.makeText(CommodityDetails.this, "修改失败!", Toast.LENGTH_SHORT).show();
} };

  

完美解决!!!

推荐阅读