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

时间:2021-05-04 20:45:18

代码改变世界

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

  

完美解决!!!