I sometimes found java.lang.IllegalStateException in my application:
java.lang.RuntimeException:
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2825)
at android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:2886)
at android.app.ActivityThread.-wrap12 (ActivityThread.java)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1623)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:186)
at android.app.ActivityThread.main (ActivityThread.java:6509)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:914)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:804)
Caused by: java.lang.IllegalStateException:
at com.****.onCreate (***.kt:35) <-- here is the Intent.getStringExtra(..)
at android.app.Activity.performCreate (Activity.java:6992)
at android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1119)
at android.app.ActivityThread.performLaunchActivity (ActivityThread.java:2778)
After i looked into it, this issue is caused by Intent.getStringExtra() with code as follows:
private lateinit var mArticle : ArticleModel
private lateinit var mArticleImg : String
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_article_detail)
val intent : Intent = this.intent;
mArticleImg = intent.getStringExtra( "articleImg" ) <-- here is where it crashed
mArticle = intent.getParcelableExtra("data")
}
Have tested this in many testing devices and could not reproduce this crash issue except when i looked into google crash report. What exactly is IllegalStateException and does this happen because of the intent return value?
You may handle possible null value with elvis operator ?:
val intent : Intent = this.intent
mArticleImg = intent.getStringExtra("articleImg") ?: "null-value-fallback"
mArticle = intent.getParcelableExtra("data") ?: "null-value-fallback"
or set the value only if it is not null, e.g. with if
or .let{..}
:
val intent : Intent = this.intent
intent.getStringExtra("articleImg")?.let { mArticleImg = it }
intent.getParcelableExtra("data")?.let { mArticle = it }
Use these checks to ensure that key is available
if (intent.hasExtra("articleImg")) {
mArticleImg = intent.getStringExtra( "articleImg" )
}
if (intent.hasExtra("data")) {
mArticle = intent.getParcelableExtra("data")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With