当尝试在数据库中插入新数据时发送此错误:“附加数据库已停止”且应用程序已关闭!
这个数据库类和插入方法:
public boolean insertUser(String userName, int age, int gender, int password, String memDescription, String pic) {
User user = null;
openDatabase();
db.beginTransaction();
try {
ContentValues values = new ContentValues();
values.put("userName", user.getUserName());
values.put("age", user.getAge());
values.put("gender", user.getGender());
values.put("password", user.getPassword());
values.put("memDescription", user.getMemDescription());
values.put("pic", user.getPic());
long result = db.insertOrThrow("tblUsers", null, values);
db.setTransactionSuccessful();
closeDatabase();
if (result == -1)
return false;
else
return true;
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "???? ??? ?? ???????");
return false;
} finally {
db.endTransaction();
closeDatabase();
}
}
和插入活动中的代码:
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
try {
boolean isInserted = DB_HELPER.insertUser(EDT_NAME.getText().toString(), Integer.parseInt(EDT_AGE.getText().toString()),
Integer.parseInt(EDT_GENDER.getText().toString()), Integer.parseInt(EDT_PASS.getText().toString()),
EDT_DESC.getText().toString(), EDT_PIC.getText().toString());
if (isInserted == true)
startActivity(new Intent(AddActivity.this, MainActivity.class));
else
Snackbar.make(view, "??? ?? ??? ????? ????!", Snackbar.LENGTH_LONG).setAction("Action", null).show();
} catch(Exception e){
e.printStackTrace();
return;
}
}
});
和这个用户表类:
public class User {
private int id;
private String userName;
private int age;
private int gender;
private int password;
private String memDescription;
private String pic;
public User(int id, String userName, int age, int gender, int password, String memDescription, String pic) {
this.id = id;
this.userName = userName;
this.age = age;
this.gender = gender;
this.password = password;
this.memDescription = memDescription;
this.pic = pic;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = password;
}
public String getMemDescription() {
return memDescription;
}
public void setMemDescription(String memDescription) {
this.memDescription = memDescription;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}