Saturday, 24 March 2012

How to avoid Force Close Error in Android


All android developer have to take care of force close issue while developing an application.here is the moetho to catch that error and solve it.It will create a error page in your application.So whenever your application is crashed user will not able to see the pop up dialig but app will display a view to the user.To do that kind of michenism we willl make error handler and an activity class which will gain the view whenever the app gets forced close.




 
 
import java.io.*;

import android.content.*;
import android.os.Process;

public class ExceptionHandler 
implements java.lang.Thread.UncaughtExceptionHandler
 {
    private final Context myContext;

    public UncaughtExceptionHandler(Context context) {
        myContext = context;
    }

    public void uncaughtException(Thread thread, Throwable exception) {
        StringWriter stackTrace = new StringWriter();
        exception.printStackTrace(new PrintWriter(stackTrace));
        System.err.println(stackTrace);

        Intent intent = new Intent(myContext, CrashActivity.class);
        intent.putExtra(BugReportActivity.STACKTRACE, stackTrace.toString());
        myContext.startActivity(intent);

        Process.killProcess(Process.myPid());
        System.exit(10);
    }
}
Above class will work as a listener for forced close error. You can see that Intent and startActivity is used to start the new Activity whenever app crashes. So it will start the activity named CrashActivity whenever app get crashed.For now I have passed the stack trace as an intent’s extras.
Now because CrashActivity is a regualr Android Actitvity you can handle it in whatever way you want.
Now comes the important part i.e. How to catch that exception.
Though it is very simple. Copy following line of code in your each Activity just after the call of super method in your overriden onCreate method.

Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
 
Your Activity may look something like this…
public class ForceClose extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Thread.setDefaultUncaughtExceptionHandler(new
         UncaughtExceptionHandler  (this));

        setContentView(R.layout.main);

        // Your mechanism is ready now.. In this activity from anywhere if
you get force close error it will be redirected to the CrashActivity.
    }
}