问题是以下代码第一次更新列值时工作得很好,但是下次拒绝增加它。
public void incrementValue(Context context, String number) {
SwipeDatabaseHelper mOpenHelper = new SwipeDatabaseHelper(
context.getApplicationContext());
String sql = "UPDATE " + DatabaseContract.PATH_CONTACTS + " SET "
+ DatabaseContract.DatabaseEntry.COLUMN_CONTACT_UNREAD + " = " +
DatabaseContract.DatabaseEntry.COLUMN_CONTACT_UNREAD + " + 1 WHERE "
+ DatabaseContract.DatabaseEntry.COLUMN_CONTACT_NUM + " = ?";
mOpenHelper.getWritableDatabase().execSQL(sql, new String[]{number});
}
非常有趣的是,当我用硬编码值(例如0)更新它时,它完美无缺。当我再次调用该函数时,它只会将其递增1,即使您将其调用一千次,该值也不会超过1
public class DatabaseHelper extends SQLiteOpenHelper {
private final static String DATABASE_NAME = "persistent.db";
private final static int CUR_DATABASE_VERSION = 4;
public SwipeDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, CUR_DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
final String CONTACTS = "CREATE TABLE USER (" +
DatabaseEntry._ID +" INTEGER PRIMARY KEY AUTOINCREMENT," +
DatabaseEntry.COLUMN_CONTACT_NUM + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_CONTACT_NAME + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COULUMN_CONTACT_SURNAME + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_CONTACT_USERNAME + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_CONTACT_UNREAD + " INTEGER NOT NULL DEFAULT 0," +
DatabaseEntry.COLUMN_CONTACT_URL + " TEXT NOT NULL DEFAULT ''," +
"UNIQUE(" + DatabaseEntry.COLUMN_CONTACT_NUM + ") ON CONFLICT REPLACE);";
final String GROUPS = "CREATE TABLE GROUPS (" +
DatabaseEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
DatabaseEntry.COLUMN_CONTACT_NUM + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_GROUP_NAME + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_GROUP_IMAGE + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_GROUP_OWNER + " TEXT NOT NULL DEFAULT ''," +
DatabaseEntry.COLUMN_CONTACT_UNREAD + " INTEGER NOT NULL DEFAULT 0," +
"UNIQUE(" + DatabaseEntry.COLUMN_CONTACT_NUM + ") ON CONFLICT REPLACE);";
db.execSQL(CONTACTS);
db.execSQL(GROUPS);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS USER");
db.execSQL("DROP TABLE IF EXISTS GROUPS");
onCreate(db);
}
}
因此同一个调用适用于User表,但对于Groups表行为异常。