A
A
Anrek2021-10-24 19:41:44
Android
Anrek, 2021-10-24 19:41:44

Why does the application crash when using a string from an enum class?

Good evening!

Why does the application crash at the array/variable initialization point when using data from the enum class?

enum class Items(@StringRes val textRes: Int) {
    Near(R.string.spinner_near),
    Rate(R.string.spinner_rate)
}

var valuesResumesSpinner = arrayOf(    // вылетает тут
        getString(Items.Near.textRes),
        getString(Items.Rate.textRes)
)


Moreover, if you put a string in the log, then everything works:
Log.i("TAG", "${getString(Items.Near.textRes)}")
and if you initialize a random variable of the String type with it, then everything also crashes:
var a: String = getString(Items.Near.textRes)

What's the matter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anrek, 2021-10-24
@Anrek

The matter was that I declared an array and a variable too directly in a class body. And this variable relies on view. And since the fragment has not yet been created, I got an error:
Fragment MainFragment not attached to a context.
The problem was solved when declaring the same array in onViewCreated.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question