10

I'm trying to get id column from my database, ad it to ArrayList and to each id add "\t0",

My database is created using Room, i have a lot of column which one of them is

@PrimaryKey(autoGenerate = true)
private int id;

I am operating using ItemDAO and i have there function

@Query("SELECT * FROM item")
List<Item> getItems();

Which writes to ArrayList<Items> all of contents I was thinking of running it trough the loop getting id and adding to ArrayList<String> but this doesn't seems to be eficient.

MMG
  • 3,226
  • 5
  • 16
  • 43
wokstym
  • 143
  • 1
  • 1
  • 12
  • 1
    Hi, welcome to Stackoverflow. Please read https://stackoverflow.com/help/how-to-ask and [edit] your question accordingly. Like: What database (SQlite, Realm, etc), how did the id get into the database? What have you tried so far? – Capricorn Aug 29 '18 at 13:03
  • How about now?? – wokstym Aug 29 '18 at 13:16

3 Answers3

15

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

Valgaal
  • 896
  • 10
  • 25
1

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!

Samuel T. Chou
  • 521
  • 6
  • 31
1

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.

Rahul Kahale
  • 519
  • 6
  • 19