Android更新记录(如果存在数据)

时间:2018-11-03 16:11:10

标签: android

我下面的代码包含在我的Android应用程序DatabaseHelper类中,目前,我已在数据库中将一行数据硬编码为Barcode(263924)Quantity(1)

但是问题是我当前正在尝试这样做,以便当用户将我硬编码的相同条形码编号添加到数据库中时,数量将+1而不创建新行。

对不起,即时通讯是Android的新功能,非常感谢!

MainActivity代码

@Override
public void handleResult(Result result) {
    final String barcodes = result.getText();
    final String quantitys = "1";
    Log.d("QRCodeScanner", result.getText());
    Log.d("QRCodeScanner", result.getBarcodeFormat().toString());

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Scan Result");
    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            scannerView.resumeCameraPreview(MainActivity.this);
        }
    });
    builder.setMessage(result.getText());
    AlertDialog alert1 = builder.create();
    alert1.show();
    AddData(barcodes,quantitys);

}

public void AddData(String barcodes,String quantitys){
    boolean insertData = myDB.addData(barcodes,quantitys);

    if(insertData==true){
        Toast.makeText(MainActivity.this,"Successfully Entered Data!",Toast.LENGTH_LONG).show();
    }else{
        Toast.makeText(MainActivity.this,"Something went wrong :(.",Toast.LENGTH_LONG).show();
    }
}

数据库代码

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "scan.db";
    public static final String TABLE_NAME = "scan_data";
    public static final String COL1 = "ID";
    public static final String COL2 = "BARCODE";
    public static final String COL3 = "QUANTITY";



    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                " BARCODE TEXT, QUANTITY TEXT)";
        db.execSQL(createTable);

        ContentValues contentValues=new ContentValues();
        contentValues.put(DatabaseHelper.COL2,263924);
        contentValues.put(DatabaseHelper.COL3,1);

        db.insert(DatabaseHelper.TABLE_NAME,null,contentValues);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean addData(String code, String quant) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, code);
        contentValues.put(COL3, quant);

        long result = db.insert(TABLE_NAME, null, contentValues);
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

    public Cursor getListContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return data;
    }
}

2 个答案:

答案 0 :(得分:1)

为此,我可以按照以下步骤操作:

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "scan.db";
    public static final String TABLE_NAME = "scan_data";
    public static final String COL1 = "ID";
    public static final String COL2 = "BARCODE";
    public static final String COL3 = "QUANTITY";



    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
                " BARCODE TEXT, QUANTITY TEXT)";
        db.execSQL(createTable);

        ContentValues contentValues=new ContentValues();
        contentValues.put(DatabaseHelper.COL2,263924);
        contentValues.put(DatabaseHelper.COL3,1);

        db.insert(DatabaseHelper.TABLE_NAME,null,contentValues);


    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
        onCreate(db);
    }

    public boolean addData(String code, String quant) {
        SQLiteDatabase db = this.getWritableDatabase();
        return isValueExists(code,db,quant);

    }

    public Cursor getListContents() {
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
        return data;
    }
    public Boolean isValueExists(String barcode,SQLiteDatabase db, String quant){
        Cursor cursor= db.query(TABLE_NAME,new String[]      {"ID"},"ID=?",new String[]{barcode},null,null,null,"1");
        if(cursor.getCount()>0){
             //if it exists then update
               try{
                    ContentValues cv = new ContentValues();
                    cv.put(COL1,cursor.getString(0));
                    cv.put(COL2,cursor.getString(1));
                  cv.put(COL3,String.valueOf(Integer.valueOf(cursor.getString(2)+1)));
                  sqLiteDataBase.update(TABLE_NAME,cv,"BARCODE=?",new String[]{barcode});
                     cursor.close();

            }catch(Exception e){}

        return true;
                }else{
                    cursor.close();
                    ContentValues contentValues = new ContentValues();
        contentValues.put(COL2, code);
        contentValues.put(COL3, quant);

        long result = db.insert(TABLE_NAME, null, contentValues);

        db.close();
        //if date as inserted incorrectly it will return -1

        if (result == -1) {
            return false;
        } else {
            return true;
        }}
            }

}

答案 1 :(得分:0)

CREATE TABLE table_name(
    id NOT NULL INTEGER PRIMARY KEY,
    ...
);

主键是一列或一组列,用于标识表中行的唯一性。每个表只有一个主键。

来源:http://www.sqlitetutorial.net/sqlite-primary-key/