Cotlin Intent, a transformation question.

Asked 2 years ago, Updated 2 years ago, 71 views

e: C:\Users\yhw\AndroidStudioProjects\MyApplication3\app\src\main\java\com\example\myapplication\ResultActivity.kt: (13, 61): Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type String?

The above is an error message. Line 13 is two lines of code source below.

    val submitText = intent.getStringExtra("submitText").toInt()
    val callText = intent.getStringExtra("callText").toInt()

There is a dot in front of the toInt(), which is underlined in red.

It's not compiling or built. Eventually, the application itself didn't work.

I programmed it just like everyone else, but I didn't know why I was the only one getting this message.

Is it a programming environment problem?

I don't think it's the ID of the view or the import or anything like that.

If you know the reason, please let me know.

kotlin

2022-09-20 20:17

2 Answers

This is because the int is nullable.

intent?getStringExtra("submitText")?.toInt()

Put a ? in front of it to make a nullable approach.

intent!!.getStringExtra("callText")!!.toInt()

You can force a non-null process by attaching !! to the front.


2022-09-20 20:17

The getStringExtra() method in the Intent class returns null if no value corresponds to the given name. https://developer.android.com/reference/android/content/Intent#getStringExtra(java.lang.String)

Therefore, when invoking int.getStringExtra(), there is no guarantee that there is a value corresponding to the name submitText or callText, so you are asked to use a null safe call (?.) or a call (!!.) stating that it is not null.

For a null safe call (?.), if the previous value is null, the subsequent content is not executed.

intent.getStringExtra("submitText")?.toInt()

/* if intent.getStringExtra ("submitText") is null
ToInt() is skipped without running. */

A call (!!.) stating that it is not null will be executed whether the previous value is null or not. If null instead, a nullPointerException exception occurs.

intent.getStringExtra("callText")!!.toInt()

/* If the intent.getStringExtra ("callText") is null,
The next time the call, toInt(), is executed,
NullPointerException exception occurs
The app will be forced to exit. */


2022-09-20 20:17

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.