Android SQLite更新方法无法更新

时间:2014-09-19 10:06:04

标签: java android database eclipse sqlite

我已经离开java一段时间了,作为一个热身,决定运行一个基本的数据库/列表保持应用程序来帮助我跟踪我移动时需要的东西。我基本上已经完成了应用程序,它运行大致但足够我的目的,但我有很多SQLite数据库功能的问题。我唯一要解决的是“更新”功能。

这是我当前的代码,在我的SQLITE Helper类中:

public int updateObject(HomeObject originalObject, HomeObject updatedObject) {
    // 1. get reference to writable DB
    SQLiteDatabase db = this.getWritableDatabase();

    // 2. create ContentValues to add key "column"/value
    ContentValues values = new ContentValues();
    values.put("name", updatedObject.getName());
    values.put("room", updatedObject.getRoom()); // get title 
    values.put("have", updatedObject.getHave()); // get author

    // 3. updating row
    int i = db.update(TABLE_HomeObjects, //table
            values, // column/value
            KEY_ID+" = "+String.valueOf(originalObject.getId()), // selections
            null ); //selection args

    // 4. close
    db.close();

    return i; 
}

但是,当我使用修改按钮来调用此方法并相应地更新对象时,它似乎只是删除该对象。它从所有列表中消失,并且应用内搜索显示它不再存在于数据库中。

以下是我用来调用它的相关代码:

MySQLiteHelper db = new MySQLiteHelper(this);
Intent intent = getIntent();
String itemName = intent.getStringExtra(LivingRoom.EXTRA_MESSAGE);

// Redacted... There is a large section of code here
// which deals with pulling the newlyEditedName, newlyEditedHave,
// and newlyEditedRoom variables from different places in the view.

HomeObject newlyEditedObject = new HomeObject(newlyEditedName, newlyEditedHave, newlyEditedRoom);
HomeObject originalObject = db.getObject(itemName);
int test = db.updateObject(originalObject, newlyEditedObject);  

我对SQLite很新,所以也许我错过了一些基本的东西......但这里出了什么问题?日志显示该方法返回“1”。另外,我可以确认“getObject”方法是完美的,因为它在此之前被多次使用,所以我知道它正确地返回。

感谢您的帮助!如果我能解决这个问题,我实际上可以开始使用这个东西。

1 个答案:

答案 0 :(得分:0)

有两种方法可以解决您的错误。 您可以将代码更改为

int i = db.update(TABLE_HomeObjects, //table
        values, // column/value
        KEY_ID+" = '"+String.valueOf(originalObject.getId()) + "'", // selections
        null ); //selection args

或者您可以使用推荐的方法

int i = db.update(TABLE_HomeObjects, //table
        values, // column/value
        KEY_ID+" =?", // selections
        new String[]{String.valueOf(originalObject.getId())} ); //selection args