How to Open/Close SQLite db in Android Properly

后端 未结 3 1596
礼貌的吻别
礼貌的吻别 2020-12-15 10:53

I have an app that functions properly and does not force close or crash. But when I look at LogCat, it occasionally gives me this:

05-20 15:24:55.338: E/SQL         


        
3条回答
  •  一生所求
    2020-12-15 11:17

    If you're using an instance of a DatabaseHelper class, and after you initialize the DBHelper object, every time you do work in the database you should call the open method before you do work, then create a new cursor, query the database, do work with the information you just stored in the cursor, when you're done close the cursor, then close the database. For example if you wanted to grab every item in a database you would do something like :

    ...    
    DataBaseHelper db = new DataBaseHelper(this);
    ... 
    db.open();
    Cursor cursor = db.getAllItems(); 
    maxCount = cursor.getCount(); 
    Random gen = new Random();
    row = gen.nextInt(maxCount); // Generate random between 0 and max
    if (cursor.moveToPosition(row)) {
        String myString = cursor.getString(1);  //here I want the second column
        displayString(myString); //private method
    }
    cursor.close();
    db.close(); 
    

    getAllItems is a public method in my DatabaseHelper, it looks like this in case you were wondering

    public Cursor getAllItems() {
        return db.query(DATABASE_TABLE, 
            new String[] {
                KEY_ROWID, 
                KEY_NAME
            }, 
            null, 
            null, 
            null, 
            null, 
            null);
    }
    

    This is how I access my database and I haven't gotten any of the errors you've got, and it works perfectly.

提交回复
热议问题