How can I change textview text with list index?

Issue

I have two activities. Im going to toss a ArrayList that has random integer numbers which is made in activity1 to another activity, named ResultActivity, by intent. Then I want to change the text of textviews of ResultActivity using the index of the list which is tossed. below is a code of ResultActivity I tried.

class ResultActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_result)

    val result = intent.getIntegerArrayListExtra("result")
    Collections.sort(result)

    val Num1=findViewById<TextView>(R.id.Num1)
    Num1.setText(result[0].toString())
}

I sorted the list after getting it from activity1.
Then a error occurs in the last " Num1.setText(result[0].toString()) " and the content of the error is below.

Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type ArrayList<Int!>?

How should I do to solve this problem?

Solution

Seems that intent.getIntegerArrayListExtra("result") returns nullable object. so, u have 2 ways:

  1. Make result not nullable by double bang:

val result = intent.getIntegerArrayListExtra("result")!!

or (more safe way) use Elvis operator:

val result = intent.getIntegerArrayListExtra("result") ?: emptyList()

  1. Work with result as with nullable list:

Num1.setText(result?.get(0)?.toString() ?: "")

Answered By – Sergei Mikhailovskii

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published