iremce iremce - 1 month ago 9
Android Question

Android fatal exception: Can't create handler inside thread that has not called Looper.prepare()

I have read similar questions about this problem and tried to find a solution but I have not figure out what is the reason in my case. My program's code rough is below :

public class ReportSystem extends Activity implements SensorEventListener , Runnable{

ReportLocation reportObj = new ReportLocation(this); //my other class
Thread thread_send = new Thread(this);

Handler handler = new Handler() {
public void handleMessage(Message message) {
msg.setText("---"));
}
};

public void onCreate(Bundle savedInstanceState){
//something...
}

public void onSensorChanged(SensorEvent event){

if(event.values[0] > 10)
thread_send.start(); // thread is started..
}

public void run(){

reportObj.send(); //connect with server and send data by the help of RepotLocation class' send function
handler.sendEmptyMessage(0);
}
}//end class


What should I do to solve this problem ?

Answer

Try this:

public void run(){
    Looper.prepare();
    reportObj.send();
    handler.sendEmptyMessage(0);
    Looper.loop();
}