tags:

views:

68

answers:

2

In my app, I'm supporting the backup and restoration of the Sqlite db file.

I need to close and re-open my database connection after the restore. How can I do this?

+1  A: 

SQLite Database class has a open and close methods.

Romain Hippeau
How do I get an instance of my SQLite db to do that?
thedude19
A: 

This code may help you.

public class DbHelper {
  private static final String DATABASE_NAME = "rayyildiz_sample.db";
  private static final int DATABASE_VERSION = 1;
  private static final String TABLE_NAME = "Test";
  private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_NAME + " ( "
      + "  \"Id\" INTEGER PRIMARY KEY,"
      + "  \"Firstname\" TEXT,"
      + "  \"Lastname\" TEXT,"
      + "  \"PhoneNumber\" TEXT" + ")";
  private static final String TABLE_INSERT = "INSERT INTO " + TABLE_NAME + "(Firstname,Lastname,PhoneNumber) VALUES (?,?,?)";

  private Context context;
  private SQLiteDatabase database;
  private SQLiteStatement insertSQLiteStatement;

  public DbHelper(Context context) {
    this.context = context;
    DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
    database = dbOpenHelper.getWritableDatabase();
    insertSQLiteStatement = database.compileStatement(TABLE_INSERT);
  }

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

  public void reopen(){
    close();
    DbOpenHelper dbOpenHelper = new DbOpenHelper(context);
    database = dbOpenHelper.getWritableDatabase();    
  }

  private static class DbOpenHelper extends SQLiteOpenHelper {
    public DbOpenHelper(Context context) {
      super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      db.execSQL(TABLE_CREATE);
    }

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