Tuesday 17 September 2013

Handle "unfortunately, App has Stopped" Or "force close " situations in android


Handle "unfortunately, App has Stopped" Or  "force close " situations in android.


Many time we forget to catch exception or some time unexpected exception occur. So we should handle in some way that our app should not show "Force Close Dialog" in such condition. 
So here is simple example. For this situations
Create Simple Class As MyExceptionHandler.

package com.example.crashhandledex;

import java.io.PrintWriter;
import java.io.StringWriter;

import android.content.Context;
import android.content.Intent;

public class MyExceptionHandler implements
              java.lang.Thread.UncaughtExceptionHandler {
       private final Context myContext;
       private final Class<?> myActivityClass;

       public MyExceptionHandler(Context context, Class<?> c) {

              myContext = context;
              myActivityClass = c;
       }

       public void uncaughtException(Thread thread, Throwable exception) {

              StringWriter stackTrace = new StringWriter();
              exception.printStackTrace(new PrintWriter(stackTrace));
              System.err.println(stackTrace);// You can use LogCat too
              Intent intent = new Intent(myContext, myActivityClass);
              String s = stackTrace.toString();
              // you can use this String to know what caused the exception and in
              // which Activity
              intent.putExtra("uncaughtException",
                           "Exception is: " + stackTrace.toString());
              intent.putExtra("stacktrace", s);
              myContext.startActivity(intent);
              // for restarting the Activity
              // Process.killProcess();
              System.exit(0);
       }
}


AND IN YOUR ACTIVITY  USED AS 


public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
              Thread.setDefaultUncaughtExceptionHandler(new MyExceptionHandler(this,
                           MainActivity.class));

              final Button button1 = (Button) findViewById(R.id.button1);
              button1.setOnClickListener(new OnClickListener() {
                     @Override
                     public void onClick(View v) {
                           //Example Crash, Here App will restart instead of showing force close dialog
                           int i = Integer.valueOf("SJDkal");
                           button1.setText(i);

                     }
              });

       }
}



Happy Codddddin :)

No comments:

Post a Comment