0

I'm working on a single-activity application while learning Android dev, and I stumbled on a roadblock, I am trying to launch/navigate to a fragment inside Thread. setDefaultUncaughtExceptionHandler when an exception is thrown, and I can't seem to get it working. I tried the following two options with the Navigation Component and the FragmentManager:

Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
    navController.navigate(R.id.exceptionFragment)
}

and

Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
    supportFragmentManager.beginTransaction().add(R.id.container, ExceptionFragment()).commit()
}

Both fail to navigate to ExceptionFragment, the app freezes.

I know that it's easily doable if the ExceptionFragment in question was an ExceptionActivity.

        Thread.setDefaultUncaughtExceptionHandler { _, throwable ->
        val intent = Intent(this@MainActivity, ExceptionActivity::class.java)
        startActivity(intent)
    }

My intention here is to send the user to another screen informing them that something went wrong with the application, and displaying a button that restarts the app (or MainActivity).

But as said previously, I want to accomplish this behavior with a fragment that's contained inside MainActivity instead. Alternatively if this can't be accomplished with fragments, I might settle with showing a dialog (if that's possible at all), while remaining on a single activity.

The question isn't about whether or not this is considered a bad practice because it obviously is, don't worry, I won't use this in production applications, I am only trying to learn more about activities, fragment, crashes in Android, for the sake of education I am asking this question to the Android gurus on Stackoverflow.

BP9381
  • 49
  • 6
  • When you try to execute a UI touching code in a thread other than main, you will get [Only the original thread that created a view hierarchy can touch its views.] (https://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi) exception. Means that the Android OS will not allow you to execute any UI modifying code from a background thread. Just execute your code and watch the logcat for this. – Kozmotronik Jul 25 '22 at 19:45
  • *My intention here is to send the user to another screen informing them that something went wrong with the application, and displaying a button that restarts the app (or MainActivity).* You can do it pretty well in main thread. To do this, you can use a similar interface logic to [this answer](https://stackoverflow.com/a/73100079/12749998). – Kozmotronik Jul 25 '22 at 19:49

0 Answers0