saxum
saxum

Reputation: 107

Storing and retrieving a directory Uri to/from SharedPreferences

I am trying to store and retrieve a directory Uri using SharedPreferences but can't get it to work.

This is my current code for persisting the directory path after the user chose a directory:

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch(requestCode) {
                case ACTIVITY_DOCUMENT_TREE:
                    if(resultCode == RESULT_OK) {
                        Uri treeUri = data.getData();
                        DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);

                        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
                        SharedPreferences.Editor editor = prefs.edit();
                        editor.putString("the_file", pickedDir.getUri().toString());
                        editor.apply();
                    }
                    break;
            }
        }

This is my current code for loading the directory from the SharedPreferences:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String path = prefs.getString("the_file", null);
// the value is:
// content://com.android.externalstorage.documents/tree/primary%3APictures%2FMyApp/document/primary%3APictures%2FMyApp
Uri uri = Uri.parse(path);
File f = new File(uri.toString());
// to test if it was successful, listFiles() - this leads to a NullPointerException
f.listFiles();
// java.lang.NullPointerException: Attempt to get length of null array

Instead of uri.toString(), I also tried uri.getPath(), with the same result.

What am I doing wrong here?

Upvotes: 2

Views: 823

Answers (1)

saxum
saxum

Reputation: 107

I got it to work now. Instead of a DocumentFile, I tried to create a regular File object from the uri string.

This is the adjusted code:

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String path = prefs.getString("the_file", null);
Uri uri = Uri.parse(path);
DocumentFile dir = DocumentFile.fromTreeUri(getActivity(), uri);
dir.listFiles(); // working fine now

Upvotes: 2

Related Questions