Home > Software engineering >  How to Make 2D ArrayList of EditText in Android Studio using Kotlin?
How to Make 2D ArrayList of EditText in Android Studio using Kotlin?

Time:04-10

'''

class MainActivity : AppCompatActivity() {
    private var button: Button? = null
    private var textList: ArrayList<ArrayList<EditText>> = arrayListOf(arrayListOf())
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        button = findViewById<Button>(R.id.solve)

          textList[0][0]=findViewById<EditText>(R.id.ed1)
          textList[0][1]=(findViewById(R.id.ed2))
          textList[0][2]=(findViewById(R.id.ed3))
          textList[0][3]=(findViewById(R.id.ed4))
          textList[0][4]=(findViewById(R.id.ed5))
}
}

'''

I wanted to Store EditText in a 2D ArrayList but Above Method dosent work. I dont know why but it crashes the app when opened. So how should i do it ?

CodePudding user response:

This:

val list: ArrayList<Int> = arrayListOf()
list[0] = 123

means "replace the item at index 0 with 123". But that's an empty list, there is no index 0. Imagine you used index 2 instead - if you could insert something there, what would be at indices 1 and 0? For something to be 3rd in a list, there needs to be a 2nd and 1st item, right?

You probably want an array instead:

private val rows = 5
private val columns = 5
private var textList: Array<Array<EditText>> = Array(rows) { arrayOfNulls(columns) }

That will create an array for each row, and it'll be filled with nulls, one for each column. Then you can assign them with findViewById (which can return null, which was another problem your ArrayList had - it could only hold non-null EditTexts)

There are probably better ways to do what you're doing, but that's your basic issue here - can't update items in a list that don't exist. And an array makes more sense for a fixed structure you're going to be accessing by index

  • Related