15

我想在我的应用程序中使用“预加载”数据库。有很多关于这个的问题,大多数都指向这里的这篇博客文章或类似文章。

到目前为止,一切都很好。我只是想知道是否有更好的方法来获取默认数据库目录,这样你就不必使用这样的东西:

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

我的意思是,也许将来会发生变化,或者设备或ROM可以将其放置在其他地方......那么有没有办法以编程方式获得这条路径?

在 Context 中存在一个 getDatabasePath(name) 的方法,但是你需要给它一个现有的数据库名称,嗯......它还不存在,我想把它移到那里:P

4

5 回答 5

11

我用了...

String destPath = getFilesDir().getPath();
destPath = destPath.substring(0, destPath.lastIndexOf("/")) + "/databases";
于 2013-05-20T20:28:09.510 回答
9

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

于 2012-10-04T08:27:49.507 回答
9

由 SQLiteAssetHelper 使用:

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

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

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

基本上,您不需要创建一个真正的数据库,只需要一个即可。

于 2014-10-07T01:05:25.907 回答
6

您可以使用方法getFilesDir()getDatabasePath在活动类中获取此文件夹。
更多信息在这里

于 2012-10-04T08:27:48.797 回答
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();
    }
于 2015-08-18T19:26:35.317 回答