2012-10-04 103 views
11

我想在我的应用程序中使用“预加载”数据库。有很多关于这个问题的问题,并且最多指向这篇博客文章here或类似的文章。以编程方式获取我的应用程序的数据库目录

到目前为止这么好。我只是想知道是否有更好的方式来获取默认的数据库目录,这样你就不必使用这样的事情:

private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/"; 

我的意思是,也许在未来,或者一个设备改变或rom可以将它放在其他地方...所以有没有办法通过编程方式获得此路径?

在上下文存在于getDatabasePath(名称)的方法,但你需要给它一个现有的数据库名称,以及...它不存在,我想将其移到:P

+0

http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-应用程序/ 9109728#9109728 –

回答

6

创建一个空数据库,与getDatabasePath()获取路径,然后用自己的覆盖。

+1

我已经这样做了......但听起来像是一个黑客:D但是......它确实有效。 –

+4

那么,因为没有官方的API来导入现成的DB文件,所以把你自己的文件也存在破解。至少你要确保你把它放在正确的地方。 –

+0

我需要写入权限吗? – Simon

6

你可以使用Activity-Class中的方法getFilesDir()getDatabasePath来获取此文件夹。
更多信息here

10

我用...

String destPath = getFilesDir().getPath(); 
destPath = destPath.substring(0, destPath.lastIndexOf("/")) + "/databases"; 
+1

不需要特别许可如果文件夹在将来的版本中发生变化,该怎么办? – pablisco

7

通过SQLiteAssetHelper使用:

String path = mContext.getDatabasePath(mName).getPath(); 

此时,数据库不存在。我认为该字符串只是内部路径并添加了适当的修饰符。事实上,这似乎只是很好地工作:

context.getDatabasePath("a").getParentFile() 

基本上,你不需要创造了一个真正的数据库,只问它一个。

+2

数据库目录可能不存在,因此在将任何内容写入/复制到context.getDatabasePath(“a”)之前,请确保检查context.getDatabasePath(“a”)。getParentFile()是否存在,是否存在该目录。 – nibarius

1

你可以在你的Helper类使用getDatabasePath方法:

public class MyDatabase extends SQLiteAssetHelper { 

    private static final String DATABASE_NAME = "wl.db"; 
    private static final int DATABASE_VERSION = 1; 
    public String databasePath = "";  

    public MyDatabase(Context context) { 
     super(context, DATABASE_NAME, null, DATABASE_VERSION); 

     // you can use an alternate constructor to specify a database location 
     // (such as a folder on the sd card) 
     // you must ensure that this folder is available and you have permission 
     // to write to it 
     // super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION); 

     databasePath = context.getDatabasePath("wl.db").getPath(); 
    } 
相关问题