How to get specific column using Android Room
I tried to modify and test @Valgaal 's solution. It turns out that Room can also return other type of values, more than just id (or integer).
For example, you can write an item class like this:
@Entity(tableName = Item.TABLE_NAME)
public class Item {
public static final String TABLE_NAME = "ItemsTable";
public static final String COL_DESC = "Description";
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = COL_DESC)
private String description;
// getter & setter...
}
And then, you can write Dao like this:
@Dao
public interface ItemDao {
@Query("SELECT * FROM " + Item.TABLE_NAME)
List<Item> getItems();
@Query("SELECT " + Item.COL_DESC + " FROM " + Item.TABLE_NAME)
List<String> getItemDescriptions();
}
And it's functional as it should be. I guess all of the other data types that Room can save (including custom types?) can be queried (and returned lists of specific column data) by the same logic above. Hope this would help someone in the future!
For returning multiple columns, create a pojo class
that can be set as a return type for your DAO function
Note the select query should contain the Pojo class variable name (can be done via AS keyword)
Detailed answer here https://stackoverflow.com/a/50802209/1029110
I landed on this question for my issue...but didnt find answer. So this may help others.
Your DAO:
@Query("SELECT Id FROM item")
List<Integer> getAllIds();
Your model:
@ColumnInfo(name = "Id")
@PrimaryKey(autoGenerate = true)
private int id;
In you query SELECT * FROM item
* means select All, put there your column name and you will get list of objects from that column
Example: Select all items in id column SELECT id FROM item