Reputation: 90
I am new to Room and it's throwing me through a loop. I am trying to take a specific row of a specific data class in my Room database and compile into a list and turn this list into a String so I can do stuff with it. I can sort of do this by printing the contents of the Room database table to the console, but that's it.
I'll show you my code
that I have
this is my data class.
code.kt
@Parcelize
@Entity(tableName = "code_table")
data class code(
@PrimaryKey(autoGenerate = true)
val id: Int,
val code: String //this is the item I want to isolate
): Parcelable
a snippet of my ViewModel.kt
that I use.
val readAllData: LiveData<List<code>>
private val repository: respository
init {
val Dao = database.getDatabase(application).dao()
repository = respository(Dao)
readAllData = repository.readAllData
}
a snippet of my repository.kt
that I use.
val readAllData: LiveData<List<code>> = dao.readAllData()
a snippet of my Dao.kt
that I use.
@Query("SELECT * FROM code_table ORDER BY id ASC")
fun readAllData(): LiveData<List<code>>
How I read the Room database table
private fun dbread(){
mUserViewModel = ViewModelProvider(this).get(ViewModel::class.java)
mUserViewModel.readAllData.observe(viewLifecycleOwner, Observer { user ->
var abc = user
println(abc)
})
}
this is what it outputs
I/System.out: [code(id=2, code=textA), code(id=3, code=textB), code(id=4, code=textC)]
I am not hell-bent on only querying the code
row but I need to aggregate all the data in the code
row into a string or JSON
array. so, in this case, that would be the textA, textB and textC (I'm worried I haven't made myself clear)
I have also tried doing the following in the Dao
@Query("SELECT code FROM code_table")
fun readdb(): LiveData<List<code>>//I've tried this with lot different types within the Parentheses
this makes the build fail: it says the following
:app:kaptDebugKotlin 1 error
java.lang.reflect.InvocationTargetException (no error message)
I would guesstimate that this error is because the SQL syntax is off but I don't think it is.
I have also tried messing around with the ViewModel
and repository
to see if I can get them to only output just the code
row but to no avail. I'm surprised I'm the first to post about this.
thank you for your time.
Upvotes: 0
Views: 2131
Reputation: 1952
You can obtain you desidered result just by using SQL. In Android (and with Room) you're using a SQLite database, so the most important thing is writing some SQL that is compliant with SQLite. Then you can select the concatenation of all the values in your table, just by asking to the database to do it. You can achieve it with this:
@Query("SELECT GROUP_CONCAT(code) FROM code_table")
fun readConcatenatedCode(): LiveData<String>
The returned value will be a LiveData of String, and the String will contain all the values, concatenated.
Upvotes: 1