Home > Enterprise >  I wish To show random Text in my splash screen's text view using kotlin
I wish To show random Text in my splash screen's text view using kotlin

Time:01-01

I'm trying to Show a random text from an array[ using kotlin ] in my splash screen [ before the MainActivity starts i suppose,] i tried ,

val thoughts = arrayOf("Trading Made Easy!","Where Smart People Trade","For Smart Traders Like You!")
    fun getRandomQuote(): String {
        val randomValue = kotlin.random.Random.nextInt(thoughts.size)
        return thoughts[randomValue]
    }
    var thought = getRandomQuote().toString()
    val textView = findViewById<TextView>(R.id.rand)
    textView.setText(thought)

But this Makes The App Close automatically instead of showing the splash screen. this line --> textView.setText(thought) has some problem because when i remove that line, the app doesn't crash and the above Function Returns a string ( i tested it with toast ) Anyway To Solve It? Or Any Other Alternate Way?

CodePudding user response:

Instead of using thoughts.size,  you should use thoughts.size-1

otherwise you might get ArrayIndexOutOfBoundsException while using thoughts[randomValue]
fun getRandomQuote(): String { val randomValue = kotlin.random.Random.nextInt(thoughts.size) return thoughts[randomValue] }

CodePudding user response:

Using setContentView(R.layout.activity_main); before trying to set A textview solved the problrm, Thank u ! override fun onCreate(savedInstanceState: Bundle?) { setContentView(R.layout.activity_main); }

  • Related