Android Studio Room and DAO: Making a query with where 'field=condition' argument

Viewed 196

In Android Studio DAO interface, this code:

@Query("SELECT COUNT(*) FROM StrategyLinks WHERE Id_Property=:condition")
    long countStrategyLinks(String condition);

Works fine when I call:

MyDao.countStrategyLinks("10");

BUT, I really want a more generic form, like this:

@Query("SELECT COUNT(*) FROM StrategyLinks WHERE :condition")
    long countStrategyLinks(String condition);

When I call:

MyDao.countStrategyLinks("Id_Property=10");

What DON'T WORK at all. There are some way to overcome this limitations? Also, is possible to pass the table name (StrategyLinks in this example) as a argument? Thanks in advance.

1 Answers

you should use RawQuery like this:

 @Dao
 interface RawDao {
   @RawQuery
   long countStrategyLinks(SupportSQLiteQuery query);
 }

 // Usage of RawDao
 SimpleSQLiteQuery query = new SimpleSQLiteQuery(
     "SELECT COUNT(*) FROM StrategyLinks WHERE ?",
     new Object[]{ condition});
 long result = rawDao.countStrategyLinks(query);
 

you can find better details in this link

Related