How using SQLiteOpenHelper with database on sd-card?

后端 未结 6 817
渐次进展
渐次进展 2021-02-08 00:50

According to various answers here and in the web extending Application and it\'s inherited method getDatabasePath() would allow to set the database storage path from the standar

6条回答
  •  悲&欢浪女
    2021-02-08 01:01

    I found I could use a full path in Android 2.2, but in 2.1 the Context.openOrCreateDatabase() method threw an exception. To work around this I wrapped that method to call SQLiteDatabase.openOrCreateDatabase() directly. Here is the constructor for my extended SQLOpenHelper

    public class Database extends SQLiteOpenHelper {
      public Database(Context context) {
        super(new ContextWrapper(context) {
            @Override public SQLiteDatabase openOrCreateDatabase(String name, 
                    int mode, SQLiteDatabase.CursorFactory factory) {
    
                // allow database directory to be specified
                File dir = new File(DIR);
                if(!dir.exists()) {
                    dir.mkdirs();
                }
                return SQLiteDatabase.openDatabase(DIR + "/" + NAME, null,
                    SQLiteDatabase.CREATE_IF_NECESSARY);
            }
        }, NAME, null, VERSION);
        this.context = context;
      }
    }
    

提交回复
热议问题