Android update row problems
In the app we are putting together I am trying to update rows from different Activities but it is throwing an error or not updating anything because I can't seem to get the current rowId once I move from one activity to the next. Any thoughts would be great.
This comes from the Activity:
Cursor value;
db.open();
long rowId = value.getLong(value.getColumnIndex("_id"));
boolean id = db.updateA(rowId, a1, a2, a3, a4);
db.close();
If I set the "rowId = 1" it updates that row just fine but I want to get the row that was just created in a different activity.
This is in the DBHelper file:
public boolean updateA(long rowId, String a1,String a2, String a3, String a4) {
ContentValues args = new ContentValues();
args.put(C_A1, a1);
args.put(KEY_A2, a2);
args.put(KEY_A3, 开发者_JS百科a3);
args.put(KEY_A4, a4);
return db.update(TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
If you need to update the record I would suggest storing the record upon creation in a data object in memory and passing that to the other Activity that needs to do the update. The data object should have a property for its own ID, so you can just use that.
Not having a reference to the record you need to update will be a disaster. Also, if you know you always need to update the record, why don't you just do it on insert?
I don't get that.
You have an activity A that opena a DB, updates a row and closes the DB. This is done with the help of SQLiteOpenHelper class.
Now you move to activity B and now what? Post your primary key (you know it, you used it an A) with putExtra to B (or just put the whole row to B). If you put the rowid to B you can open, reread the row, update if needed and close again. If you just put the whole row to B, well that's all you need to do - but I wouldn't like that (e.g. what happens if B crashes?).
If you update in both activities without knowledge what both activities did (and without re-reading the rows) it's pure luck what you end with.
Try this:
return db.update(TABLE, args, KEY_ROWID + "='" + rowId + "'", null)
精彩评论