android - 使用 Room 复制 Android 中的值在 Insert 命令上传递列表

标签 android android-room

我正在传递国家/地区的国家/地区列表,以使用 Room 将其保存在数据库中。它保存了,但它复制了值,并且 OnConflict Replace 策略不起作用。

AppDatabase.getAppDatabase(getApplicationContext()).countryDao().insertAllList(countryList);

即使我传递了以下替换策略,列表值也会重复。

@Insert(onConflict = OnConflictStrategy.REPLACE)

这里是 CountryDao

@Dao
public interface CountryDao {

@Query("SELECT * FROM country")
List<Country> getAllCountries();

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAllList(List<Country> countries);

}

国家/地区对象:

 @Entity(tableName = "country")
    public class Country {
    public int getId() {
        return id;
    }

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

    @PrimaryKey(autoGenerate = true)
    private int id;
    private long countryId;
    private String countryName;

    public long getCountryId() {
        return countryId;
    }

    public void setCountryId(long countryId) {
        this.countryId = countryId;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

最佳答案

您必须为每个国家/地区拥有不同的 ID 并手动分配它,否则每个元素将具有 id=0 并覆盖另一个元素。

尝试不使用自动生成 key

@PrimaryKey(autoGenerate = false)
private int id;

关于android - 使用 Room 复制 Android 中的值在 Insert 命令上传递列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45691276/

相关文章:

iphone - 哪个移动系统适合程序员?

android - 当多个 gmail 处于 Activity 状态时处理 C2DM 注册

java - 将带有字符串的枚举写入包裹

android - Kotlin + Room : java. lang.IllegalArgumentException:void 无法转换为 Element

android - 是否可以在 Room 中忽略基本更新中的字段

android - 从房间数据库中删除数据

android - EditText 中左侧可绘制对象和文本之间的间隙

java - 一个 Android 应用程序中的多个应用程序文件

java - 错误 : Entities and Pojos must have a usable public constructor.

android - 如何在 Android Room 中创建部分索引