Search code examples
javaandroidandroidx

How can I share a db file between 2 applications


since Enviroment.getExternalStorageDirectory() is deprecated I have a little Problem. I have 2 applications (a lite and a pro version of an app). These apps have a database which I could export and import. When switching from lite to pro app, the user could import the "old" database into the new app. The database was stored under a folder inside his "sdcard". But now on Android 12 devices we no longer have access to that External Storage.

So how could I solve the problem?

Cause I think, context.getExternalFilesDir((Environment.DIRECTORY_DOCUMENTS) doesn't work cause the namespace of both apps are different. And I guess it will not work to open a file which is not located under the namespace of the app the file is requested.


Solution

  • I found a solution by myself, but if someone else is looking for a solution it might be helpful.

    I ask the user to specify a file location via

    Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    intent.setType("application/db");
    intent.putExtra(Intent.EXTRA_TITLE, "xyz.db");
    
    mCreateNewDatabaseFile.launch(intent);
    

    then in the mCreateNewDatabaseFile

    private final ActivityResultLauncher<Intent> mCreateNewDatabaseFile = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
        if (result.getResultCode() == RESULT_OK) {
            if (result.getData() != null && result.getData().getData() != null) {
                Uri path = result.getData().getData();
                getContentResolver().takePersistableUriPermission(path, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                getContentResolver().takePersistableUriPermission(path, Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mPreferences.edit().putString(PREF_KEY_DATABASE_EXPORT_PATH, path.toString()).apply();
            }
        }
    });
    

    So even with another process I can read and write the file.

    So in the lite Version I can create the db file and in the pro version I can let the user choose this file for import.

    I hope it will help others with similar questions.