Skip to content Skip to sidebar Skip to footer

Android Catch Unhandled Exception And Show The Dialog

I want to handle unhandled exception in my app without any third-party libraries. So i write a code. Activity : @Override public void onCreate(Bundle savedInstanceState) { supe

Solution 1:

In my case, I moved AlertDialog.Builder in thread run function like this:

public void showToastInThread(final String str){
    new Thread() {
        @Override
        public void run() {
            Looper.prepare();

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setMessage("Application was stopped...")
            .setPositiveButton("Report to developer about this problem.", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                }
            })
            .setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    // Not worked!
                    dialog.dismiss();
                    System.exit(0);
                    android.os.Process.killProcess(android.os.Process.myPid());

                }
            });

            dialog = builder.create();


            Toast.makeText(context, "OOPS! Application crashed", Toast.LENGTH_SHORT).show();
            if(!dialog.isShowing())
                dialog.show();
            Looper.loop();

        }
    }.start();
}

and all thing work perfectly.

Hope this help you.


Solution 2:

According this post, the state of the application is unknown, when setDefaultUncaughtExceptionHandler is called. This means that your onClick listeners may not be active anymore.

Why not use this method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        setContentView(R.layout.main);
        Thread.setDefaultUncaughtExceptionHandler(new ReportHelper(this));
        throw new NullPointerException();
    } catch (NullPointerException e) {
        new ReportHelper(this);
    }
}

and remove ReportHelper implementing the Thread.UncaughtExceptionHandler interface.

Your method of not explicitly catching exceptions can be seen as an anti-pattern.


Solution 3:

Since an exception occurs on the UI-Thread: the state of this thread is probably unexpected

So try simply this in your click handler :

.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    android.os.Process.killProcess(android.os.Process.myPid());

                }
            });

Post a Comment for "Android Catch Unhandled Exception And Show The Dialog"