2012-06-04 59 views
1
@Override 
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory){ 
     File externalFilesDir = Environment.getExternalStorageDirectory(); 
     if(externalFilesDir == null) 
       return null; 
     File dbFile = new File(externalFilesDir, SQLiteHelper.DATABASE_NAME); 
     return SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY); 
    } 

我使用上面的代碼將我的db文件寫入外部存儲。所以它被保存在/mnt/sdcard/。當我在Android 2.3.5中嘗試它時,它可以工作。但是對於Android 4,它不起作用。但它仍然不會給我任何錯誤。爲什麼我的外部數據庫在Android 4中無法訪問?

+0

您是否使用了write_external_storage權限? Eight

+0

是的。這在Android 2.3.5中正常工作,但不在4中 – dinesh707

回答

2

這是一些其他人尋找相同的東西的答案。

// ======= This will allow to create the DB in /mnt/sdcard/ 
    // External folder DB access for Android 4+ 
     @Override 
     public SQLiteDatabase openOrCreateDatabase(String name, int mode,CursorFactory factory, DatabaseErrorHandler errorHandler) { 
      File externalFilesDir = Environment.getExternalStorageDirectory(); 
      if(externalFilesDir == null) 
        return null; 
      File dbFile = new File(externalFilesDir, SQLiteHelper.DATABASE_NAME); 
      return super.openOrCreateDatabase(dbFile.getAbsolutePath(), Context.MODE_WORLD_WRITEABLE, null, errorHandler); 
     } 

     // External folder DB access for Android 2.3 
    @Override 
    public SQLiteDatabase openOrCreateDatabase(String name, int mode, CursorFactory factory){ 
     File externalFilesDir = Environment.getExternalStorageDirectory(); 
     if(externalFilesDir == null) 
       return null; 
     File dbFile = new File(externalFilesDir, SQLiteHelper.DATABASE_NAME); 
     return SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.CREATE_IF_NECESSARY); 
    } 
相關問題