向/从SharedPreferences存储和检索目录Uri

时间:2018-07-04 00:27:30

标签: android sharedpreferences uri storage

我正在尝试使用SharedPreferences存储和检索目录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;
            }
        }

这是我当前用于从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

我也尝试了uri.getPath(),而不是uri.toString(),结果相同。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:0)

我现在开始工作了。我尝试使用uri字符串创建常规File对象,而不是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