Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/194.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在SharedReferences中存储和检索目录Uri_Android_Sharedpreferences_Uri_Storage - Fatal编程技术网

Android 在SharedReferences中存储和检索目录Uri

Android 在SharedReferences中存储和检索目录Uri,android,sharedpreferences,uri,storage,Android,Sharedpreferences,Uri,Storage,我正在尝试使用SharedReferences存储和检索目录Uri,但无法使其正常工作 这是我当前用于在用户选择目录后保留目录路径的代码: @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case ACTIVITY_DOCUMENT_TREE

我正在尝试使用SharedReferences存储和检索目录Uri,但无法使其正常工作

这是我当前用于在用户选择目录后保留目录路径的代码:

        @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;
            }
        }
这是我从SharedReferences加载目录的当前代码:

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
我还尝试了uri.getPath(),而不是uri.toString(),结果相同


我做错了什么?

我现在让它工作了。我尝试从uri字符串创建常规文件对象,而不是DocumentFile

这是调整后的代码:

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

路径中的值是多少?是否已调试并检查?是,路径的值为:content://com.android.externalstorage.documents/tree/primary%3APictures%2FMyApp/document/primary%3APictures%2FMyAppI 将此信息添加到问题中。