Search code examples
androidarraylistkotlinparcelable

Android kotlin: putParcelableArrayList(ArrayList<int>) and getParcelableArrayList<Int>() wont work


I am trying to pass ArrayList<Integer> from fragment to another fragment, here is my code:

Kotlin code

companion object {
    fun newInstance(categoryId: Int, brandsList: ArrayList<Int>): Fragment {
        val fragment = CategoryAllAdsFragment()
        fragment.arguments = Bundle()
        fragment.arguments!!.putInt(Constant.CATEGORY_ID, categoryId)
        fragment.arguments!!.putParcelableArrayList(Constant.BRANDS_LIST, brandsList)
        return fragment
    }
}

but it says:

Type mismatch.

Required: java.util.ArrayList !

Found: kotlin.collections.ArrayList /* = java.util.ArrayList */

The same thing when I was trying to read it.

Kotlin code

try {
    val brandsList = arguments!!.getParcelableArrayList<Int>(Constant.BRANDS_LIST)
} catch (ex: Exception) {
    throw Exception("brand list cannot be null")
}

It says:

Type argument is not within its bounds

Expected: Parcelable!

Found: Int

I've tested it with Java and its work fine.


Solution

  • Use

    • putIntegerArrayList(String key, ArrayList value)

    • Inserts an ArrayList value into the mapping of this Bundle, replacing any existing value for the given key

    putIntegerArrayList(Constant.BRANDS_LIST, array)
    

    And get like

    • getIntegerArrayList(String key)

    • Returns the value associated with the given key, or null if no mapping of the desired type exists for the given key or a null value is explicitly associated with the key.

    extras.getIntegerArrayList(Constant.BRANDS_LIST)