HelloCW
HelloCW

Reputation: 2285

How can I query a record of part fields using Room in Android Studio with Kotlin?

It works well to query record MVoice using fun listVoice():LiveData<List<MVoice>> with Room framework in Android Studio with Kotlin.

Now I hope to query record of part fields (Such as ID and name) of MVoice, how can I do?

interface DBVoiceDao{
   @Query("SELECT * FROM voice_table ORDER BY createdDate desc")
   fun listVoice():LiveData<List<MVoice>>

   /*  How can I do this?
   @Query("SELECT id, name FROM voice_table ORDER BY createdDate desc")
   fun listVoiceOfPartField():LiveData< ??? >
   */
}



@Entity(tableName = "voice_table", indices = [Index("createdDate")])
data class MVoice(
    @PrimaryKey (autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0,
    var name:          String = "Untitled",
    var path:          String = "My path",
    var createdDate:   Calendar = Calendar.getInstance(),
    var isStar:        Boolean = false,
    var description:   String="My description"
)

Upvotes: 0

Views: 56

Answers (1)

Muhammad Farhan
Muhammad Farhan

Reputation: 1291

As "Florina Muntenescu" suggested that Read only what you need in this article 7 Pro-tips for Room

You can achieve it by making a new Model Class:

data class VoiceMinimal(@ColumnInfo(name = "id") val id: Int,
                        @ColumnInfo(name = "name") val name: String)

In the DAO class, we define the query and select the right columns from the voice table.

@Dao
interface DBVoiceDao {
    @Query(“SELECT id, name FROM voice_table ORDER BY createdDate dESC)
    fun getVoiceMinimal(): List<VoiceMinimal>
}

Upvotes: 1

Related Questions