Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why context.startActivity(intent) not starting the activity and how to handle exception in android?

I have an exception handler which handles exception from an Activity class, the exception handler looks like this.

public class ExceptionHandler implements Thread.UncaughtExceptionHandler {
    public static final String TAG = "Exception handler";
    private final Context activity;

    public ExceptionHandler(Context activity) {
        this.activity = activity;
    }

    @Override
    public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
        Intent error = new Intent(activity, ErrorCatcher.class);
        activity.startActivity(error);
    }
}

it is initialized from the activity class

  @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.e(TAG, "onRestart: Hey just created");
        Thread.setDefaultUncaughtExceptionHandler(new ExceptionHandler(this.getApplicationContext()));
// other methods and function
}

when the control comes to the exception handler, the activity is not created, instead of a blank page that hangs my app.

The only message I get is

I/Timeline: Timeline: Activity_launch_request time:417281208 intent:Intent { cmp=com.yyy.xxx/com.yyy.xxx.Activities.Error }

EDIT: Ok, after some digging I find, if no exception is thrown then the activity is started (i.e I can see the Activity page) but when an exception is thrown that's when a blank page is displayed. Why is this the condition for only when an exception is thrown and what is a better way to handle exception in android?? any help?


EDIT 2 : it's similar to this https://codecrunch.co/blog/custom-error-handling-in-android/

like image 286
Akash Jain Avatar asked Aug 10 '20 20:08

Akash Jain


2 Answers

before the startActivity, add error.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);. There are also more complete answers here

like image 70
Leonardo Goes Avatar answered Oct 20 '22 02:10

Leonardo Goes


This code may be helpful for you

Application application = (Application) context.getApplicationContext();
Intent intent = new Intent(application, ErrorActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
application.startActivity(intent);

If not then notify me, I will send you complete code for exception handling!

like image 34
Abdur Rehman Avatar answered Oct 20 '22 02:10

Abdur Rehman