Sujin Shrestha
Sujin Shrestha

Reputation: 1253

Android Room Fetch data with dynamic table name

Is it possible to fetch data by passing the table name as a parameter? Something like this.

@Query("SELECT id, name from :tableName")
fun getData(tableName: String): List<RandomModel>

Upvotes: 9

Views: 3289

Answers (3)

Angel Koh
Angel Koh

Reputation: 13505

you first create in your Dao a @RawQuery. just Class1, Class2, etc with the tables/classes that you are interested to monitor.

@RawQuery(  observedEntities = [Class1::class, CLass2::class]  )
fun query(query:SupportSqliteQuery): List<RandomModel>

To use it just create a SimpleSqliteQuery with the necessary input argument.

note there is a difference between "SupportSqlite..." used in Dao and "SimpleSqlite..." used in the doQuery() function

fun doQuery(tableName:String):List<RandomModel> {

    //note $ sign in front of tableName instead of : sign
    val simpleSqliteQuery =  SimpleSqliteQuery("SELECT id, name from $tableName") 
    return dao().query( simpleSqliteQuery  )
}

Upvotes: 0

milad salimi
milad salimi

Reputation: 1660

I think Room does not support dynamic tableName.

We have two ways:

1-In DAO, we can replace tableName with the actual table name, as defined on the model @Entity

2-We can use @RawQuery like this :

@Dao
 interface RawDao {
     @RawQuery
     User getUserViaQuery(SupportSQLiteQuery query);
 }
 SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE id = ? LIMIT 1",
         new Object[]{userId});
 User user2 = rawDao.getUserViaQuery(query);

You can study more at this

Upvotes: 1

sadat
sadat

Reputation: 4342

Try this

@Dao
interface RawDao {
 @RawQuery
 List<RandomModel> getData(SupportSQLiteQuery query);
}

 SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM "+ tablename);
 List<RandomModel> models = rawDao.getUserViaQuery(query);

Upvotes: 4

Related Questions