I have a custom ArrayList and String ArrayList in my Android application. I am using one for-loop for adding custom list values to sqlite. I also remove rows in the custom ArrayList which will match with the value of the String ArrayList before adding to sqlite. I have to use two for-loops for this matter. Can I achieve this inside the sqlite adding loop?
ArrayList<String> localRefNoList = new ArrayList<>();
ArrayList<SynchronizDTO> arr_sync = new ArrayList<>();
public class SynchronizDTO {
private String userName;
private String referenceNo;
private String employeeNo;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getReferenceNo() {
return referenceNo;
}
public void setReferenceNo(String referenceNo) {
this.referenceNo = referenceNo;
}
public String getEmployeeNo() {
return employeeNo;
}
public void setEmployeeNo(String employeeNo) {
this.employeeNo = employeeNo;
}
}
for (int i = 0; i < arr_sync.size(); i ) {
for (String ss : localRefNoList) {
if (ss.equals(arr_sync.get(i).getReferenceNo().trim())) {
arr_sync.remove(i);
}
}
}
for (int i = 0; i < arr_sync.size(); i ) {
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.userName, arr_sync.get(i).getUserName().trim());
cv.put(DatabaseHelper.referenceNo, arr_sync.get(i).getReferenceNo().trim());
cv.put(DatabaseHelper.employeeNo, arr_sync.get(i).getEmployeeNo().trim());
try {
restoreLogRes = db.insertOrThrow(DatabaseHelper.tbl_sms, null, cv);
} catch (Exception ex) {
}
}
CodePudding user response:
You can add a flag variable to do this in one go. And it will be much more intuitional if you do it on the removing loop rather than sqlite adding loop. Here I am optimizing a little bit. Also remember don't call for (int i = 0; i < arr_sync.size(); i ) here. It will calculate list size again and again. Rather do this :
int length = arr_sync.size();
for (int i = 0; i < length; i ) {
boolean flag = true;
for (String ss : localRefNoList) {
if (ss.equals(arr_sync.get(i).getReferenceNo().trim())) {
arr_sync.remove(i);
flag = false;
break;
}
}
if(flag){
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.userName, arr_sync.get(i).getUserName().trim());
cv.put(DatabaseHelper.referenceNo,
arr_sync.get(i).getReferenceNo().trim());
cv.put(DatabaseHelper.employeeNo, arr_sync.get(i).getEmployeeNo().trim());
try {
restoreLogRes = db.insertOrThrow(DatabaseHelper.tbl_sms, null, cv);
} catch (Exception ex) {
}
}
}