0

I am trying to show the alert dialog in the if condition.

ObdGatewayService.java

 public class ObdGatewayService{

 if(e.getMessage().equals("Broken pipe")){
            ((MainActivity) ctx).OBDreconnect();
            }
 } 

MainActivity.java

   public void OBDreconnect() {
    if(!show_obd_reconnect_dialog) {
        AlertDialog.Builder build = new AlertDialog.Builder(this);
        build.setMessage(R.string.obd_losted)
                .setCancelable(false)
                .setPositiveButton("Reconnect", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        startLiveData();
                    }
                })
                .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        finish();
                    }
                });
        show_obd_reconnect_dialog = true;
        build.show();
    }
}

getting error below :

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
GNK
  • 1,036
  • 2
  • 10
  • 29
  • 1
    you can't do UI stuff on a background thread. [check this](https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare) – Vucko Sep 01 '20 at 11:27
  • Thank you. Now it is working. – GNK Sep 01 '20 at 11:39

1 Answers1

0
  if(e.getMessage().equals("Broken pipe")){
                Handler handler = new Handler(Looper.getMainLooper());
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ((MainActivity) ctx).OBDreconnect();

                    }
                }, 0 );
            }
GNK
  • 1,036
  • 2
  • 10
  • 29