1

I am trying to add two shops to a mutable list like so:

private var _shopList =  MutableLiveData<List<Shop>>()
    var shopList: LiveData<List<Shop>> = ()
        get() = _shopList


    // This function will get the arrayList items
    fun getArrayList(): MutableLiveData<List<Shop>>
    {


        // Here we need to get the data
        val shop1 = Shop("AOB", "Lat and Long","LA")
        val shop2 = Shop("Peach", "Lat and Long","Vegas")



        _shopList.add(shop1)
        _shopList.add(shop2)



        return _shopList
    }

However it says the add function is not referenced?

Lyndon2309
  • 49
  • 8

2 Answers2

1

From docs:

List: A generic ordered collection of elements. Methods in this interface support only read-only access to the list; read/write access is supported through the MutableList interface.

MutableList: A generic ordered collection of elements that supports adding and removing elements.

You can modify a MutableList: change, remove, add... its elements. In a List you can only read them.

Solution -

 private var _shopList = MutableLiveData<List<Shop>>() // List is fine here as read only
val shopList: LiveData<List<Shop>>  // List is fine here as read only
    get() = _shopList


// This function will get the arrayList items
fun getArrayList(): MutableLiveData<List<Shop>> {
    // Here we need to get the data
    val shop1 = Shop("AOB", "Lat and Long", "LA")  //  var to val
    val shop2 = Shop("Peach", "Lat and Long", "Vegas") //var to val

    _shopList.value = mutableListOf(shop1, shop2) // assigns a mutable list as value to the live data which can be observed in the view

    return _shopList
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Abhishek Dubey
  • 937
  • 8
  • 11
  • Thank you, please check your solution. I don't think the change you reffering to was made? – Lyndon2309 Sep 06 '20 at 11:37
  • It gives two errors. 1) the get() function on the immutable shopList says theres a type mismatch. 2) the add function still throws an error? Theres probably something small we are missing here because I get the idea behind what you're saying. – Lyndon2309 Sep 06 '20 at 11:45
  • I will delete these comments once we find the mistake – Lyndon2309 Sep 06 '20 at 11:46
0

Here is the solution:

private var _shopList =  MutableLiveData<MutableList<Shop>>()
val shopList: LiveData<MutableList<Shop>> 
    get() = _shopList


// This function will get the arrayList items
fun getArrayList(): MutableLiveData<MutableList<Shop>>
{


    // Here we need to get the data
    var shop1 = Shop("AOB", "Lat and Long","LA")
    var shop2 = Shop("Peach", "Lat and Long","Vegas")


    _shopList.value = mutableListOf(shop1,shop2)

    return _shopList
}
Lyndon2309
  • 49
  • 8