I know there are lots of similar question to mine but for my situation none of them worked!
I have table with 4 columns and I have set @PrimaryKey(autoGenerate = true) private int id;
for my ID and @index unique
for my other 3 column , Something like this :
@Entity(tableName = "Data" ,
indices = {@Index(value = {"name","data","label"}, unique = true)})
public class Data {
@PrimaryKey(autoGenerate = true)
private int id;
private String name;
private String data;
private String label;
public Data(String name, String data, String label) {
this.name = name;
this.data = data;
this.label = label;
}
and for my Dao I have set (onConflict = OnConflictStrategy.REPLACE)
for my Insert query , also It should be Sayed that I have test With OnConflictStrategy.IGNORE
and it Didn't even show the Table in App inception :
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Data data);
and finally in my MainActivity
class I have my String Data that is 2d array next to my inserting method :
db = AppDatabase.getAppDatabase(this);
dataDao = db.getDataDao();
ArrayList<Data> dataList = new ArrayList<>();
try {
for (int i = 0; i < stringData.length;) {
data = new Data(stringData[i][0],stringData[i][1],stringData[i][2]);
dataDao.insert(data);
i ;
}
}catch (Exception e){
Log.e(TAG, "onCreate: ", e);
}
I have test and debug my app several times the only thing I got was Error for version number that I forgot to increase! in picture below u can see that my ID got duplicated and it start from 687!
I'd suggest uninstalling the app and trying again, after amending the errant line 216 (see below). I'd also suggest using OnConflictStrategy.IGNORE
and also utilising:-
@Insert(onConflict = OnConflictStrategy.IGNORE)
long insertIgnore(Data data);
If the value returned from the insert is -1 then the row would not have been inserted due to the UNIQUE constraints.