I.T. Navigate
I.T. Navigate

Reputation: 31

How do I migrate from ArrayList<Object> to Android LiveData<List<Object>> from a Room database?

I am updating some Kotlin to use LiveData. From:

    var words: ArrayList<Word> = ArrayList()
    :
    :
    for (word: Word in words) {
            createEntry(word)
    }

To:

    lateinit var words: LiveData<List<Word>>
    :
    words = WordRoomDatabase.getDatabase(application,scope).wordDao().getAll()
    :
    // How do I loop through all the words?

I've tried :

    for (word: Word in words) {
    }

but this fails as words doesn't have an 'iterator()' method.

    @Entity
    data class Word(
            @PrimaryKey(autoGenerate = true)
        var id: Long?,
        @NonNull
        var name: String?
        ) : Parcelable {
        constructor(parcel: Parcel) : this(
            parcel.readValue(Long::class.java.classLoader) as? Long,
            parcel.readString()
        )
        override fun writeToParcel (parcel: Parcel, flags: Int) {
        :
        :
        }
        companion object CREATOR : Parcelable.Creator<Word> {
            override fun createFromParcel(parcel: Parcel): Word{
                return Word(parcel)
            }
            override fun newArray(size: Int): Array<Word?> {
                return arrayOfNulls(size)
            }
        }
    }

In the database world, I'd use a cursor, however, I can't figure out how to make cursors work with an iterator() either. I can declare it in the DAO, but how do I use it?

    @Dao
    interface WordDao {
        @Query("SELECT * FROM Word")
        fun getAll(): LiveData<List<Word>>

        @Query("SELECT * FROM Word")
        fun getCursorAll(): LiveData<Cursor>
    }

e.g. If I try

    words = WordRoomDatabase.getDatabase(application,scope).wordDao().getCursorAll()

I still get the missing iterator() method error.

Do I need to create an iterator() method, or, I suspect more likely, what is the correct way to iterate through LiveData from a Room database?

I'm guessing something like:

    val iterator = wordObserver.iteratorWithAdditions()
    while (iterator.hasNext()) {
    :
    }

but in this case, how do I set up the Observer?

Upvotes: 0

Views: 935

Answers (1)

Andrei Tanana
Andrei Tanana

Reputation: 8442

LiveData is a stream of events. So you cannot use LiveData> exactly the same as List. For example, you can subscribe to this stream and process events in this stream like this

packData.observe(yourActivity, Observer { words ->
    if (words != null) {
        for (word: Word in words) {
            ...
        }
    }
})

Upvotes: 3

Related Questions