Api 29(Android Q)的外部应用程序目录中的SQLiteOpenHelper

时间:2019-09-30 22:15:06

标签: java android sqlite sqliteopenhelper android-10.0

如何针对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的Public Documents文件夹中创建数据库?

感谢您的关注

1 个答案:

答案 0 :(得分:1)

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

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