All Android developers must face a serious problem when developing an application. Here is a method to catch this error and treat it elegantly.
This will create an error page type mechanism in your Android app. Therefore, whenever your application crashes, the user will not be able to see this annoying pop-up dialog. Instead, the application displays a preview of the user.
To create such a mechanism, we need to make one error handler and the Activity class, which will get a view when the application is forcibly closed.
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); }}
The above class will work as a listener for a forced close error. You can see that Intent and startActivity are used to start a new action every time the application crashes. Thus, he will start working with the name CrashActivity whenever the application is broken. At the moment, I went through the stack trace as additional jobs.
Now, since CrashActivity is a regualr of Android Actitvity, you can handle it in any way.
Now comes the important part, that is, how to catch this exception. Although it is very simple. Copy the following line of code in each of your activities immediately after calling the super method in your override onCreate method.
Thread.setDefaultUncaughtExceptionHandler (new UncaughtExceptionHandler (this));
Your activity might look something like this ...
public class ForceClose extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this)); setContentView(R.layout.main);
you can download the zip file from this link
http://trivedihardik.wordpress.com/2011/08/20/how-to-avoid-force-close-error-in-android/