Fazil fazi
Fazil fazi

Reputation: 459

how to use distinct in android room

I am using android room instead of sqllite. In my application database column have multiple records. For example my column name is country. The values are

I want the result is

The Qatar and Germany cames more than times. I want sort out to single item. I have used SELECT DISTINCT name from country. But it showing errors . My code is shown on below.

CountryDao.java

@Dao
public interface CountryDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void addCountry(Country country);  
@Query("SELECT DISTINCT name from country")
public List<Country> getCountry();
}

Country.java

@Entity
public class Section {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;

    public Section(int id, String name){
    this.setId(id);
    this.setName(name);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

It's shows the error is The columns returned by the query does not have the fields [id] in com.android.db.Country even though they are annotated as non-null or primitive. Columns returned by the query: [name]

AppDatabase.java

@Database(entities = {Country.class}, version = 5, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase{
private static AppDatabase INSTANCE;
public abstract ClassDao classDao();
public abstract SessionDao sessionDao();
public abstract SectionDao sectionDao();
public static AppDatabase getDatabase(Context context) {
    if (INSTANCE == null) {
       INSTANCE =
                Room.databaseBuilder(context, AppDatabase.class, "edumiadatabase").fallbackToDestructiveMigration()
                        .build();
    }
    return INSTANCE;
}

public static void destroyInstance() {
    INSTANCE = null;
}
}

In my activity getting data by adding this code. ``List co = database.countryDao().getCountry();

Upvotes: 12

Views: 9571

Answers (2)

Fazil fazi
Fazil fazi

Reputation: 459

I got the answer by making changes I have change the query in CountryDao.java . rewrite the query to

@Query("SELECT DISTINCT name from country")
public List<String> getCountry();

Then call in the activity like this.

 List<String> co = database.countryDao().getCountry();
    for(int i=0; i<co.size();i++) {
        Log.d(TAG, "country:" + co.get(i));
    }

It's the problem is in my code get the list by object but i want it in strings. Thanks for all frienda.

Upvotes: 18

Rajesh Wolf
Rajesh Wolf

Reputation: 1005

List items = database.countryDao().getCountry(); List of strings use for loop here to iterate

Upvotes: 1

Related Questions