使用sqlite数据库时close()光标和DB

时间:2012-11-06 10:33:09

标签: android database sqlite cursor

在我的应用程序中,我使用sqlite Database,当我运行应用程序时,Logcat显示我

close() was never explicitly called on database '/data/data/com.MAT.CanadaImmigrationApp/databases/CanadaianImmigrationApp' 
E/Database(13822): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here

我在google上搜索,然后找到了

db.close();  // to close your Database,
cur.close();     //to close your cursor

但我不知道我在哪里添加这段代码?

DbHelper.class

public class DbHelper extends SQLiteOpenHelper {
// Database attributes

public static final String DB_NAME = "DB_NAME";
public static final int DB_VERSION = 1;

public static final String TABLE_QUESTIONS = "Questions_Answers";
public static final String COLUMN_CHAPTERS = "Chapters";
public static final String COLUMN_QUESTIONS = "Question";
public static final String COLUMN_CORRECT_ANSWER = "Correct_Answer";
public static final String COLUMN_OPT1 = "Answer1";
public static final String COLUMN_OPT2 = "Answer2";
public static final String COLUMN_OPT3 = "Answer3";

public DbHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {


    String createTable = "create table if not exists " + TABLE_QUESTIONS + " ( " + BaseColumns._ID + " integer primary key autoincrement, " 
                                                            + COLUMN_CHAPTERS + " text not null, "
                                                            + COLUMN_QUESTIONS + " text not null, "
                                                            + COLUMN_CORRECT_ANSWER + " text not null, "
                                                            + COLUMN_OPT1 + " text not null, "
                                                            + COLUMN_OPT2 + " text not null, "
                                                            + COLUMN_OPT3 + " text not null);";

    // Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS "+ TABLE_QUESTIONS);
    onCreate(db);
}

}

Db_Adapter.class

 public class Db_Adapter  {

public static final String TABLE_QUESTIONS = "Questions_Answers";
public static final String COLUMN_CHAPTERS = "Chapters";
public static final String COLUMN_QUESTIONS = "Question";
public static final String COLUMN_CORRECT_ANSWER = "Correct_Answer";
public static final String COLUMN_OPT1 = "Answer1";
public static final String COLUMN_OPT2 = "Answer2";
public static final String COLUMN_OPT3 = "Answer3";


public static  SQLiteDatabase databasesql;
private  DbHelper Android_OpenDb_Helper;
private   Context mycontext;

public static List<String> question_Set;
public static List<String> Answers_Set;
public static List<String> Option1;
public static List<String> Option2;
public static List<String> Option3;


public Db_Adapter( Context context)
{
    this.mycontext =context;
}
public void close() {
    Android_OpenDb_Helper.close();
  }

public DbHelper createDatabase()
{
    Android_OpenDb_Helper = new DbHelper(mycontext);
    databasesql = Android_OpenDb_Helper.getWritableDatabase();
    return Android_OpenDb_Helper;

} 

public long addToDB(String chapters, String question,
        String correctAnswer, String answer1, String answer2, String answer3)
{
    return databasesql.insert(TABLE_QUESTIONS,null, createContentValues(chapters,question,correctAnswer,answer1,answer2,answer3));
} 

  private ContentValues createContentValues(String chapters, String question,
        String correctAnswer, String answer1, String answer2, String answer3)
{
    ContentValues myContentVal =  new ContentValues();
    myContentVal.put(COLUMN_CHAPTERS, chapters);
    myContentVal.put(COLUMN_QUESTIONS, question);
    myContentVal.put(COLUMN_CORRECT_ANSWER, correctAnswer);
    myContentVal.put(COLUMN_OPT1, answer1);
    myContentVal.put(COLUMN_OPT2, answer2);
    myContentVal.put(COLUMN_OPT3, answer3);


    return myContentVal;
} 

public Cursor readData()
{
    return databasesql.query(TABLE_QUESTIONS, new String[]{COLUMN_CHAPTERS,COLUMN_QUESTIONS,COLUMN_CORRECT_ANSWER,COLUMN_OPT1,COLUMN_OPT2,COLUMN_OPT3}, null, null, null, null, null);
}

public Cursor getQuestion()
{
    return databasesql.query(TABLE_QUESTIONS, new String[]{COLUMN_QUESTIONS}, null, null, null, null, null); 
}

public Cursor getQuizQuestions(int numQ)
{
    return databasesql.rawQuery(
            "select * from "+ TABLE_QUESTIONS +" ORDER BY RANDOM() LIMIT "
                    + numQ, null);
}

public List<String> getQuestions(String difficulty) {

    question_Set = new ArrayList<String>();
    Answers_Set = new ArrayList<String>();

    Option1= new ArrayList<String>();
    Option2 = new ArrayList<String>();
    Option3 = new ArrayList<String>();



    Cursor c = databasesql.rawQuery(
            "select * from "+TABLE_QUESTIONS+" where CHAPTERS = ?",
            new String[] { difficulty });

    while (c.moveToNext()) {

        question_Set.add(c.getString(2).trim());
        Answers_Set.add(c.getString(3).trim());
        Option1.add(c.getString(4).trim());
        Option2.add(c.getString(5).trim());
        Option3.add(c.getString(6).trim());


    }

    return question_Set;
} 

public int DropTable()
{

    return databasesql.delete(TABLE_QUESTIONS, null, null);
} 

}

我称之为:

获得问题:

Cursor cursor = DB_Adapter.getQuestion();     

获取插入:

DB_Adapter.addToDB(Chapters,Question,CorrectAnswer,Answer1,Answer2,Answer3);

请告诉我在哪里可以添加 db.close(); cur.close();

感谢。

4 个答案:

答案 0 :(得分:2)

致电: -

DB_Adapter.addToDB(Chapters,Question,CorrectAnswer,Answer1,Answer2,Answer3); 
**db.close();**

答案 1 :(得分:2)

关闭CursorDatabase object.

的方法有两种

第一种方式 使用后关闭对象(即每当完成与光标相关的过程时)

第二种方式

OnStop()onDestroy()中添加。

OnStop()onDestroy()中检查游标和数据库对象是否为空。如果没有,请关闭它。

public void onStop(){
 if(db!=null)
   {db.close();}
 if(cur!=null)
  { cur.close();}
}

它应该有用。

答案 2 :(得分:1)

使用此方法创建数据库

我的构造函数

&#13;
&#13;
public DBClass(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		
		this.context = context;
		
		
		
	
		
	}
&#13;
&#13;
&#13;

&#13;
&#13;
@Override
	public void onCreate(SQLiteDatabase db) {
		
		context.openOrCreateDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null);
		db.execSQL("CREATE TABLE IF NOT EXISTS prediction(country1 VARCHAR,Country2 VARCHAR,winner VARCHAR,pool VARCHAR);");
	}
&#13;
&#13;
&#13;

然后在您的数据库中访问函数使用像这样的

&#13;
&#13;
public void databaseInsertOperations(String c1, String c2, String c3) {
		db = this.getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put(DBClass.COUNTRY_1, c1);
		cv.put(DBClass.COUNTRY_2, c2);
		cv.put(DBClass.WINNER, c3);
		db.insert(DBClass.TABLE, null, cv);
		db.close();
	}

	public ArrayList<String> databaseRetriveOperation() {

	
		db = this.getWritableDatabase();
		
		ArrayList<String> buffer = new ArrayList<String>();

cursor = db.rawQuery("select * from prediction", null);

		if (cursor.getCount() == 0) {
			System.out.println("Error No records found");

		} else {

			while (cursor.moveToNext()) {
				buffer.add(cursor.getString(0) + "/" + cursor.getString(1)
						+ "/" + cursor.getString(2));
			}
			
		}
		
		db.close();		cursor.close();
		return buffer;

	}
&#13;
&#13;
&#13;

当我收到此错误时

为我工作

答案 3 :(得分:0)

尝试这种情况:

如果您想使用数据库帮助功能访问或触发任何查询,请使用打开数据库。

使用该功能或​​查询后,始终关闭该数据库。

e.g:

db.open(); // function to open database for the use
db.YOUR_QUERY or ANY_FUNCTION
db.close();

打开和关闭数据库用于以可写/可读的方式打开数据库并关闭它。

您可以使用以下函数进入databaseHelper类来打开和关闭数据库。

 //---opens the database---
public DBAdapter2 open() throws SQLException 
{
        db = DBHelper.getWritableDatabase();

    return this;
}

//---closes the database---    
public void close() 
{
    DBHelper.close();
}

希望它会对你有所帮助。

<强>更新

改变这个:

    question_Set.add(c.getString(2).trim());
    Answers_Set.add(c.getString(3).trim());
    Option1.add(c.getString(4).trim());
    Option2.add(c.getString(5).trim());
    Option3.add(c.getString(6).trim());

以下:

        db.open();
    question_Set.add(c.getString(2).trim());
    db.close();
    db.open();
    Answers_Set.add(c.getString(3).trim());
    db.close();
    db.open();
    Option1.add(c.getString(4).trim());
    db.close();
    db.open();
    Option2.add(c.getString(5).trim());
    db.close();
    db.open();
    Option3.add(c.getString(6).trim());
    db.close();