简体   繁体   中英

How to close the database connection in Android

Currently working on database part of android project. The main aim of the project is to parse the XML file and store the database as its parsing. I am opening the database and inserting the data in database. But when I try to change the activity it crashes on close() function of database. I know I am doing something wrong here. If anyone can help me here it will be great.

/ * DatabaseManager.java * /

    SQLiteDatabase db;
public DatabaseManager(Context context){
    this.context = context;

    db = context.openOrCreateDatabase(DATABASE_NAME, 0, null);
    }

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

/ ** Activity.java ** /

 public void onCreate(Bundle savedInstanceState) {

    try{
        super.onCreate(savedInstanceState);
        DB = new DatabaseManager(this);
     }
  }

 public void onDestroy(){
     super.onDestroy();

    if(DB!=null)
        DB.close();
 }

Errors:

 E/Database(676): close() was never explicitly called on database '/data/data/org.com.android/databases/MainSQLite.db' 
enter code here

Looking at your code you are closing out the Db correctly because of you are calling super.onDestroy(); before the code gets to call the db.close() method.

Try calling it outside the onDestroy() method.

this is what im duing :-)

private DbHelper ourHelper;



private static class DbHelper extends SQLiteOpenHelper{

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        // TODO Auto-generated constructor stub
    }}

public void close(){
     ourHelper.close();
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM