Reputation: 39
I would like to check whether a record exists or not.If exist , i want to add the quantity.
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty = Integer.parseInt(rQty + etQty.getText().toString());
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
}
Here is the code.if insert the same code of item , the data become duplicate and it not add the quantity for the same code.Please help me to solve this problem .
Upvotes: 3
Views: 391
Reputation: 4520
There are multiple errors and bugs in your code. One problem is this code
rQty = Integer.parseInt(rQty + etQty.getText().toString());
It won't add qQty with input quantity. because here strings concatenated. You have to use
rQty += Integer.parseInt (qty);
Second one is your sqlite query is not right and it is incomplete so change
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE " + code + "'", null);
to
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
Try below code
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String code = etCode.getText().toString();
String product = etProduct.getText().toString();
String qty = etQty.getText().toString();
try {
if (isExist(code)) {
rQty += Integer.parseInt (qty);
} else {
myDB.addData(code, product, Integer.parseInt(qty));
Toast.makeText(MainActivity.this, "Data Inserted", Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Error", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean isExist(String code) {
boolean result;
SQLiteDatabase db = myDB.getReadableDatabase();
try {
Cursor cursor = db.rawQuery("SELECT QTY FROM users_data WHERE CODE = '" + code + "'", null);
if (cursor.getCount() > 0 ){
while (cursor.moveToFirst()){
rQty = cursor.getInt(cursor.getColumnIndex("QTY"));
}
result = true;
}else {
result = false;
}
}
catch (Exception ex){
result = false;
}
return result;
}
Upvotes: 1