duongluu
duongluu

Reputation: 33

Hashmap with ArrayList data type (Kotlin)?

This is the variables and addControl fun I used.

var arrayTQ = ArrayList<TongQuan>()
var arrayBG = ArrayList<BangGia>()
var epdbLV: ExpandableListView? = null
var listHeader: List<String> = listOf()
var listChild = HashMap<String, ArrayList<Any>>()

var arrayListData = ArrayList<String>()
private fun addControl() {
    epdbLV = findViewById(R.id.epdbList)
    listHeader = ArrayList()
    listChild = HashMap<String, ArrayList<Any>>()
    listHeader = listOf("Tổng Quan Thị Quan Thị Trường, Bảng Giá, Lịch Sự Kiện, Tin Tức, Chỉ Số Thế Giới")
    arrayListData = ArrayList()
    arrayTQ = ArrayList()
    arrayBG = ArrayList()
}

And I put the listChild.put into override fun in inner class GetData extend AsyncTask. The error at arrayTQ is about the type of data TongQuan not match with Any. In Java, It is no need to add typedata after ArrayList in HashMap. Help me fix it, I had searched and tried. Thanks Guys.

override fun onPostExecute(result: ArrayList<String>) {
        super.onPostExecute(result)
        getDataTQ()
        getDataBG()
        listChild.clear()
        listChild.put(listHeader.get(1), arrayTQ)
    }

Upvotes: 2

Views: 9023

Answers (2)

hakim
hakim

Reputation: 3909

Any is different with Object in Java. Unlike in java where every class is child of Object, in kotlin not every class is child of Any.

Instead of using ArrayList, you should use kotlin List. it should work like this:

ar arrayTQ = mutableListOf<TongQuan>()
var arrayBG = mutableListOf<BangGia>()
var epdbLV: ExpandableListView? = null
var listHeader: List<String> = listOf()
var listChild = HashMap<String, List<Any>>()

var arrayListData = mutableListOf<String>()
private fun addControl() {
    epdbLV = findViewById(R.id.epdbList)
    listHeader = ArrayList()
    listChild = HashMap<String, List<Any>>()
    listHeader = listOf("Tổng Quan Thị Quan Thị Trường, Bảng Giá, Lịch Sự Kiện, Tin Tức, Chỉ Số Thế Giới")
    arrayListData.clear()
    arrayTQ.clear()
    arrayBG.clear()
}

it should be safe to call

override fun onPostExecute(result: ArrayList<String>) {
        super.onPostExecute(result)
        getDataTQ()
        getDataBG()
        listChild.clear()
        listChild.put(listHeader.get(1), arrayTQ)
    }

as @Henry suggest, you should read kotlin Variance https://kotlinlang.org/docs/reference/generics.html

Upvotes: 0

Henry
Henry

Reputation: 17851

ArrayList<TongQuan> is not a child of ArrayList<Any>.

So instead of this: listChild = HashMap<String, ArrayList<Any>>()

you should have: listChild = HashMap<String, ArrayList<TongQuan>>()


However, this will let you add only ArrayList<TongQuan>. If you want the ability to add ArrayList<TongQuan> or ArrayList<BangGia>, then you need to do the below:

listChild = HashMap<String, ArrayList<out Any>>()

For a detailed documentation on Variance, refer here: https://kotlinlang.org/docs/reference/generics.html

Upvotes: 3

Related Questions