首页 > 解决方案 > Api 29 (Android Q) 的外部应用程序目录中的 SQLiteOpenHelper

问题描述

我该如何为android Q(Api 29)做以下情况?

我的意图是保留在卸载应用程序后将继续存在的目录中。

它具有以下类及其构造函数:

    public class SqlHelper extends SQLiteOpenHelper {
    //constructor
     SqlHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

    //rest of the class

    }

在我的 DAO 中调用数据库时:

public class Dao {

    private Context context;
    protected SQLiteDatabase db;

    public Dao(Context context) {
        this.context = context;
    }

    protected void openDataBase() {
        String pathDB = FOLDER_NAME_DBASE;
        //getExternalStorageDirectory() deprecated Api 29
        File dir = new File(Environment.getExternalStorageDirectory(), pathDB);


        String dBasePath = dir.getPath() + "/" + mydatabse.db3;

        SqlHelper varHelp = new SqlHelper(
                context,
                dBasePath,
                null,
                DBASE_VERSION
        );

        db = varHelp.getWritableDatabase();
    }

   //rest of the class

}

使用 SQLiteOpenHelper 有没有办法在 Api 29 的公共文档文件夹中创建数据库?

感谢您的关注

标签: javaandroidsqlitesqliteopenhelperandroid-10.0

解决方案


将实时 SQLite 数据库放在外部存储上对于任何版本的 Android 来说都是不明智的。数据损坏的风险更大,因为其他应用程序可能会尝试使用该文件。

但是,如果您希望忽略该建议,您可以getExternalFilesDir()在 Android 10 上将其用作数据库的基本目录。用户可以访问它,尽管位置不太友好。


推荐阅读