1.这是我用 DBController 编写的代码片段:
public boolean insertReport(String item_ean) {
SQLiteDatabase db = this.getWritableDatabase();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date();
ContentValues contentValues = new ContentValues();
contentValues.put(ITEM_EAN, item_ean);
contentValues.put(DATE,dateFormat.format(date));
long result = db.insert(TABLE_REPORT, null, contentValues);
if (result==-1){
return false;
}
else {
return true;
}
}
2.这是在我的 MainActivity 类
中boolean isInserted = dbcontroller.insertReport(editText.getText().toString());
if (isInserted = true){
Toast.makeText(Search.this, "Data inserted", Toast.LENGTH_LONG).show();
}
else {
Toast.makeText(Search.this, "Data not inserted", Toast.LENGTH_LONG).show();
}
selected = pselected;
textView.setText("ITEM UNKNOWN");
selected.clear();
textView.setTextColor(Color.RED);
所以在上面的代码中我给出了一个数字,即 12345678 ,它在数据库中搜索。如果找不到该号码,则会显示 ITEM UNKNOWN 。现在我想根据搜索结果插入数字。如果item未知,那么我应该在表中插入“5”。这是我的参考。
答案 0 :(得分:0)
鉴于您在评论中提到的条件,您必须像以下一样修改insertReport
:
public boolean insertReport(String item_ean) {
SQLiteDatabase db = this.getWritableDatabase();
SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date=new Date();
long result;
// This line queries your DB to see if the item_ean already exists, 1 means yes, 0 means no
Cursor cursor = db.query(TABLE_REPORT,
new String[]{"NUMBER"}, "NUMBER = ?",
new String[]{item_ean}, null, null, null);
// Value is already present, no need to insert again but you need to
// update the prediction value to 1 from 5
if (cursor.getCount() == 1) {
ContentValues contentValues = new ContentValues();
contentValues.put(prediction, "1");
result = db.update(TABLE_REPORT, contentValues, "NUMBER = ?", new String[]{item_ean});
}
// Value is not present because getCount was 0.
else {
ContentValues contentValues = new ContentValues();
contentValues.put(ITEM_EAN, item_ean);
contentValues.put(DATE,dateFormat.format(date));
contentValues.put(prediction, "5");
result = db.insert(TABLE_REPORT, null, contentValues);
}
if (result==-1){
return false;
}
else {
return true;
}
}
注意:我假设item_ean
是唯一的,因此,db.query
只会找到一个或没有,并返回cursor
一个{ {1}}值为1或0.