2 Steps to solve problem:Can’t create handler inside thread that has not called Looper.prepare() in Android



Today when i programming a android project, i met with this problem:

Can’t create handler inside thread that has not called Looper.prepare()

From the error message, we should create a handler after calling Looper.prepare.

However, i know i have not used handler in code snippet when problem occurred.

This code snippet is:

new Thread() {
 @Override
 public void run() {
 super.run();
 String url = HaikangVideoManager.getRTSPURL(cameraID);
 if("".equals(url)) {
 Toast.makeText(context, "url invalid", Toast.LENGTH_LONG).show();
 return;
 }
 mLiveControl.setLiveParams(url, HaikangVideoManager.mName, HaikangVideoManager.mPassword);
 if(mLiveControl.LIVE_PLAY == mLiveControl.getLiveState()){
 mLiveControl.stop();
 }
 if (mLiveControl.LIVE_INIT == mLiveControl.getLiveState()) {
 mLiveControl.startLive(surfaceView);
 }
 }
 }.start();

How to solve this problem? you can do as follow step.

Step 1: Find position of problem occurred

Only when i find position of problem occurred, we can solve this problem easily, by logcat tool in  eclipse, we can find it very easily.

Step 2: Analysis this problem and Solve it

By Logcat tool, i know this problem occurred in Toast.makeText(context, “url invalid”, Toast.LENGTH_LONG).show();

Then i know why this problem occurred, because Tost.make should be run in main thread in android, but no in a sub thread.

To solve this problem is very simple, remove Toast.makeText(context, “url invalid”, Toast.LENGTH_LONG).show();