My first Android application and I seem to be complete lost in the Uri, path and Android file system structure maze. :-
My application allows users to export data into a file. I created a directory picker which allows the user to select a folder and stores the string converted uri in preferences, like so:
case R.id.action_directoryPicker: {
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
i.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(Intent.createChooser(i, "Choose directory"), 9999);
return true;
}
....
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 9999) {
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Uri treeUri = data.getData();
if (treeUri == null) {
return;
}
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(SettingsActivity.KEY_PREF_IMPORT_EXPORT_LOCATION, treeUri.toString());
editor.apply();
}
}
This works fine! Now, I'd like to set the default to the downloads folder when the app is started for the first time, which is when things go wrong. I have the following code in mainActivity.onCreate()
# Now some conversion madness:
# Convert environment string into a file
# Convert file into a uri
# Convert uri into a string again so I can store it in preferences
File f = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
Uri u = Uri.fromFile(f);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(SettingsActivity.KEY_PREF_IMPORT_EXPORT_LOCATION, u.toString());
editor.apply();
}
Even though it's ugly, it works in principle. However, the string/uri I am getting from Environment.DIRECTORY_DOWNLOADS
is different to what I would get when manually picking the Download folder via my filePicker routine.
What it should read to work: content://com.android.providers.downloads.documents/tree/downloads
What I get from Environment.DIRECTORY_DOWNLOADS
and fails: file:///storage/emulated/0/Download
So after all this context, my question is what's the best way to get to the proper Uri reflecting a device download folder?