Reputation: 2896
Sometimes, the setGraph function causes a NullPointerException: null cannot be cast to non-null type kotlin.Int. It depends on how I restart the application.
When MainActivity is created, it programmatically sets the graph and start destination. Basically, it decides whether the user is logged in or not. If logged in, then it goes to HomeFragment. If not, it shows LoginFragment.
Here is my function that sets the graph and start destination:
private fun openLogin(navGraph: NavGraph, navigateToChatAutomatically: Boolean) {
navGraph.setStartDestination(R.id.login_nav_graph)
try {
navController.setGraph(
navGraph,
bundleOf(
"pageCount" to 3,
"navigateToChatAutomatically" to navigateToChatAutomatically
)
)
}catch (t: Throwable){
//exception java.lang.NullPointerException: null cannot be cast to non-null type kotlin.Int
}
}
When I restart activity this way, activity restarts and user gets NullPointerException when setGraph is called inside openLogin
function.
fun FragmentActivity.restart(){
val intent = this.intent
finish()
startActivity(intent)
}
I don't know the exact reason why the exception occurs when the activity is restarted. I've only found a working solution (see the answer below). If anyone knows why this happens or maybe there's a better solution, please let me know.
Upvotes: 0
Views: 641
Reputation: 2896
When I restart the application from scratch by restarting its process, the application restarts and setGraph
works well without any exceptions.
fun FragmentActivity.rebirth(){
ProcessPhoenix.triggerRebirth(this)
}
And this is the library I use to restart the process:
implementation("com.jakewharton:process-phoenix:2.1.2")
Upvotes: -1