Android更新时间戳

时间:2018-11-06 08:38:24

标签: android timestamp

我下面的代码是我的DatabaseHelper,我有一个允许用户插入数据的函数,但是当前我要实现的问题是更新我的COL4(这是我的TIMESTAMP)尝试添加此代码contentValues.put(COL4, " time('now') ");,但仅打印出time('now')。任何帮助将不胜感激,谢谢!

   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 static final String COL4 = "TIMESTAMP";



    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, TIMESTAMP DATETIME DEFAULT (DATETIME(CURRENT_TIMESTAMP, 'LOCALTIME')))";
        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);

        String[] params = new String[]{code};
        Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE " 

+ COL2 + " = ?", params);
            long result;
            if (data.getCount() > 0) {
                data.moveToFirst();
                String[] args = new String[]{data.getString(0)};
                contentValues.put(COL3, (Integer.parseInt(data.getString(2)) + Integer.parseInt(quant)));

               contentValues.put(COL4, " time('now') "); // THIS LINE HERE

                result = db.update(TABLE_NAME, contentValues, COL1 + "=?", args);
        } else {
            contentValues.put(COL3, quant);
            result = db.insert(TABLE_NAME, null, contentValues);
        }
        //if date as inserted incorrectly it will return -1
        if (result == -1) {
            return false;
        } else {
            return true;
        }
    }

1 个答案:

答案 0 :(得分:1)

您的代码在这里有逻辑错误

您将time('now')作为值而不是变量传递。 您需要做的就是通过输入

这样的值来获取当前时间的值。
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());