2017-07-07 73 views
0

我有一个名为MainExerciseDatabaseOne.db的sqlite数据库文件存储在我的app/src/main/assets/databases文件夹中。我想在我的主要活动的功能,打开文件:无法在android中加载数据库文件

private ExerciseDb createDatabase(){ 
    final String inFileName = "/data/data/<mypackage>/databases/MainExerciseDatabaseOne.db"; 
    File dbFile = new File(inFileName); 
    FileInputStream fis = null; 
    try { 
     fis = new FileInputStream(dbFile); 
    } catch (FileNotFoundException e) { 
     Log.e("error",e.toString()); 
    } 
    String outFileName = DB_PATH + ExerciseDb.DATABASE_NAME; 
    // Open the empty db as the output stream 
    OutputStream output = null; 
    try { 
     output = new FileOutputStream(outFileName); 
    } catch (FileNotFoundException e) { 
     Log.e("error",e.toString()); 
    } 
    // Transfer bytes from the inputfile to the outputfile 
    byte[] buffer = new byte[1024]; 
    int length; 
    try { 
     while ((length = fis.read(buffer))>0){ 
      output.write(buffer, 0, length); 
     } 
    } catch (IOException e) { 
     Log.e("error",e.toString()); 
    } 

    // Close the streams 
    try { 
     output.flush(); 
     output.close(); 
     fis.close(); 
    } catch (IOException e) { 
     Log.e("error",e.toString()); 
    } 
    ExerciseDb ret = new ExerciseDb(this); 
    return ret; 
} 

,但我得到未发现异常就行了文件:

fis = new FileInputStream(dbFile); 

在每一个教程中,我看这似乎是访问这个文件的正确路径,所以我不确定它为什么不能正常工作。这也是奇怪,因为这个确切的代码没有工作,直到我卸载了我的手机上的应用程序,并做了一个干净的构建,并从Android Studio中重新安装应用程序

+0

只需使用[SQLiteAssetHelper(http://jgilfelt.github.io/android-sqlite-asset-helper/),而不是 –

回答

0

尝试:

  1. 使用你的软件包的名称(例如,com.example.package )代替myactivity in /data/data/com.example.package/databases/MainExerciseDatabaseOne.db
  2. 使用mkdirs代替/data/data/com.example.package/databases/。我不确定这个目录是否默认存在。没有extention
  3. 使用文件(只是一个建议):MainExerciseDatabaseOne.db> MainExerciseDatabaseOne
+0

你能解释一下你的#2是什么意思? – Mike

+0

@Mike,在使用'FileInputStream'之前创建所有父目录 – Vyacheslav

0

MainExerciseDatabaseOne.dbapp/src/main/assets/databases不会让它自动拷贝到应用数据库位置(/data/data/<mypackage>/databases/MainExerciseDatabaseOne.db)。数据库仍在您的应用程序中。

我曾尝试过同样的事情(包括数据库)。这是我如何做到的。

MainExerciseDatabaseOne.dbapp/res/raw/。然后,您可以通过文件流访问数据库并将其复制到应用程序数据库位置。

try{ 
    File db = new File(DB_PATH + ExerciseDb.DATABASE_NAME) 
    InputStream in = context.getResources().openRawResource(R.raw.ExerciseDb) 
    final FileOutputStream out = new FileOutputStream(dbFile); 
    final byte[] buff = new byte[1024]; 
    int read; 
    while ((read = in.read(buff)) > 0) { 
     out.write(buff, 0, read); 
    } 
    in.close(); 
    out.close(); 
} catch (IOException ignored) { 
} 

然后,您可以使用MainExerciseDatabaseOne.db姓名SQLiteOpenHelper正常访问它。

如果你坚持使用资产文件夹,你可以试试这个。我做了测试,但它应该工作。

InputStream in = context.getResources().getAssets().open("MainExerciseDatabaseOne.db")