Im running into an issue inserting items into my database. It really odd that the program will run through 4 rows and insert them fine, but on the 5th row it crashes and I got three reports of Application did not close cursor or database. In my code I am closing and reopening both the cursor and the database so I am really confused on how this is happening. Here is the code.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case REQUEST_CODE_NEW:
if (resultCode == -1) {
Integer chapterId = data.getIntExtra("chapterId", -1);
Toast toast = Toast.makeText(this, "Selected Chapter: " + chapterId.toString(), Toast.LENGTH_LONG);
if (chapterId != -1) {
DbHelper db = new DbHelper(this);
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}
toast.show();
}
break;
}
}
Thats calling the database to be created through a dbhelper class. Here is the database helper
public void insertQuestion(String cat_id, String title, String answer, String article) {
db.execSQL("INSERT INTO " + QUESTION_TABLE_NAME + " (title,answer,article,picture) VALUES ('" + title + "','" + answer + "','" + article + "','none')");
String id = getQuestionId(title);
db.execSQL("INSERT INTO " + REL_TABLE_NAME + " (question_id, cat_id) VALUES (" + id + "," + cat_id + ")");
}
public String getQuestionId(String title) {
String id;
cursor = this.db.rawQuery("SELECT question_id FROM " + QUESTION_TABLE_NAME + " WHERE title = '" + title + "' LI开发者_StackOverflow社区MIT 1", null);
cursor.moveToFirst();
id = cursor.getString(0);
cursor.close();
db.close();
return id;
}
I put the cursor at the class level so I can try to manage it better, but still to no avail. Its still crashing after 4 queries.
Try this "fix":
DbHelper db = new DbHelper(this);
try{
for (int i = 0; i < questions.getTitle().size(); i++) {
db.insertQuestion(chapterId.toString(), questions.getTitle().get(i), questions.getAnswer().get(i), questions.getAr().get(i));
}
}catch(Exception e1){
android.util.Log.v("DbHelper Error","Crash: "+e1.getMessage(), e1);
}finally{
db.close();
}
精彩评论