2017-08-15 24 views
2

傳遞列表我通過countryList國家將其保存在數據庫使用房間。它的保存,但它的重複值和OnConflict替換策略不起作用。插入命令使用房間複製Android中的值

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); 

}

Country對象:

@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; 
    } 
} 

回答

3

你必須有不同的ID對每個國家和手動指定,否則每個元素都會有id = 0並覆蓋另一個。

嘗試沒有自動生成密鑰

@PrimaryKey(autoGenerate = false) 
private int id; 
+0

沒有 - 它不工作,事實上存在的兩個列表中,但其存儲一個值 – nauman

+0

你一定要爲每個國家不同的ID,否則每一個元素都會有標識= 0並覆蓋另一個。 – kkk