首页 > 解决方案 > 显示 0 的行数

问题描述

即使在成功插入数据后计数也显示为 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 这意味着它的插入但是当我调用 count 方法时它显示 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;
}

活动

int profile_counts = myDBHlpr.getProfilesCount();
    Log.d("BLAHHHHHHH", String.valueOf(profile_counts));

标签: javaandroidsqlsqlite

解决方案


有了这个

db2.update()

您不是在表中插入行,而是在更新现有行。
你必须使用

db2.insert()

插入新行。
db2.update()返回更新的行数。
在您的情况下,因为它返回的表中没有行0
因此,当您将结果与-1失败进行比较时,您会看到ufToast。
如果没有更新的行返回0

所以这样做:

long returnVariable2 = db2.insert(TABLE_USER_DATA, null, contentValues2);

db2.insert()-1如果过程不成功,则返回。


推荐阅读