即使插入数据成功,计数仍显示为 0
MainData helper2 = new MainData(this); //Change the name to your Helper Class name
SQLiteDatabase db2 = helper2.getWritableDatabase();
int userData = 0;
Cursor data2 = helper2.getUserData();
while (data2.moveToNext()) {
userData = data2.getInt(data2.getColumnIndex("MessagesSent"));
}
ContentValues contentValues2 = new ContentValues();
contentValues2.put(KEY_ID, MessageRecieverId);
contentValues2.put(KEY_NAME, MessageRecieverName);
contentValues2.put(KEY_MESSAGES_SENT, userData+1);
long returnVariable2 = db2.update(TABLE_USER_DATA, contentValues2, null, null);
if (returnVariable2 == -1) {
Toast.makeText(getApplication(), "Nope", Toast.LENGTH_LONG).show();
//-1 means there was an error updating the values
} else {
Toast.makeText(getApplication(),"uf", Toast.LENGTH_SHORT).show();
}
它显示 uf,这意味着它正在插入,但是当我调用计数方法时它显示 0 行...有人可以帮我吗
计数
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_USER_DATA;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int count = cursor.getCount();
cursor.close();
return count;
}
Activity
int profile_counts = myDBHlpr.getProfilesCount();
Log.d("BLAHHHHHHH", String.valueOf(profile_counts));
最佳答案
有了这个
db2.update()
您不是在表中插入行,而是更新现有行。
你必须使用
db2.insert()
插入一个新行。
db2.update()
返回更新的行数。
在您的例子中,因为表中没有行,它返回 0
。
因此,当您将结果与 -1
进行比较时,它会失败并且您会看到 uf
Toast。
如果没有更新的行返回 0
。
所以这样做:
long returnVariable2 = db2.insert(TABLE_USER_DATA, null, contentValues2);
db2.insert()
如果过程不成功则返回 -1
。
关于java - 显示 0 的行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53487743/