Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room database: how to retrieve column names into list of strings?

Tags:

android-room

I have a Room table named "addresses" with 15 columns. I retrieve one row and want to get values into List< String >, not List< Addresses >. Is that possible?

@Query("SELECT * FROM addresses WHERE myid= :id")
List<String> getAddressAsList(int id);

Moreover, is it possible to retrieve database table column names together with values into list of map <"column name","value"> like this?

@Query("SELECT * FROM addresses WHERE myid= :id")
List<Map<String, String> getAddressAsList(int id);
like image 464
Taha Avatar asked Nov 07 '22 00:11

Taha


1 Answers

You can use a SupportSQLiteDatabase but not a Dao.

Say you have, in an activity,

db = yourRoomDatabase.getInstance(this);
  • i.e. you'd typically then use something like yourDao = db.getYourDao(); and then myAddressList = dao.getAddressList();

You can then do:-

SupportSQLiteDatabase sdb = db.getOpenHelper().getWritableDatabase();
Cursor csr = sdb.query("SELECT * FROM address WHERE myid=?",new String[]{String.value(id)}

Then to get the list of column names in the Cursor you can use:-

    val columnNames = csr.columnNames

To get the Map of columnnames and values you could use :-

    val columnsAndValues: MutableMap<String,String> = mutableMapOf()
    while (csr.moveToNext()) {
        for (i: Int in 0..csr.columnCount) {
            columnsAndValues.put(csr.columnNames.get(i),csr.getString(i))
        }
    }
    csr.close()
like image 125
MikeT Avatar answered Dec 14 '22 11:12

MikeT