我有一个带有列" id INTEGER PRIMARY KEY AUTOINCREMENT"的数据库表。当我尝试使用主键更新此表的现有行时,应用退出说"不幸的是停止。"
public int updateUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_FIRSTNAME, user.getUser_firstName()); // user first name
values.put(KEY_LASTNAME, user.getUser_lastName()); // user first name
values.put(KEY_USERNAME, user.getUsername());
values.put(KEY_PASSWORD, user.getPassword());
values.put(KEY_USERLEVEL, user.getUser_level());
values.put(KEY_DESIGNATION, user.getDesignation());
values.put(KEY_MOBILENO, user.getMobile_no());
values.put(KEY_EMAIL, user.getEmail());
values.put(KEY_NIC, user.getNIC());
values.put(KEY_GENDER, user.getGender());
values.put(KEY_DOB, user.getDOB());
values.put(KEY_AVAILABILITY, user.getAvailability());
db.close();
// updating row
return db.update(TABLE_USERS, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser_id()) });
Logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.projectmanagementsys.com.sasith.project_management/com.projectmanagementsys.com.sasith.project_management.AddUser}: java.lang.IllegalStateException: attempt to re-open an already-closed object: SQLiteDatabase: /data/data/com.projectmanagementsys.com.sasith.project_management/databases/ProjectManagement
整个事情没有错误,当我评论更新查询时代码运行良好。有人可以给出解决方案吗? 谢谢。
答案 0 :(得分:2)
您的行db.close()
后跟db.update()
,并且您的错误表明您正在尝试打开已经关闭的对象。在您添加了数据后,您还没有关闭数据库,之前您已将其关闭。您需要更新该行,关闭数据库,然后返回您的值。
// updating row
int result = db.update(TABLE_USERS, values, KEY_ID + " = ?",
new String[] { String.valueOf(user.getUser_id()) });
db.close();
return result;