android - 在 SharedPreferences 中存储和检索目录 Uri
问题描述
我正在尝试使用 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.toString(),我还尝试了 uri.getPath(),结果相同。
我在这里做错了什么?
解决方案
我现在开始工作了。我尝试从 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
推荐阅读
- javascript - Vue 和 Axios,这个回调的东西让我很困惑。错误:'v-on 处理程序中的错误:“TypeError:无法读取未定义的属性'成功'”'
- python - 你能从一个 h5py 对象写一个 h5 文件吗?
- android - 将 Firebase 动态链接粘贴到 Chrome 地址栏中会打开 Playstore 而不是应用
- git - git status 只打印目录级别信息
- java - 为什么递归方法的输出会发生变化?
- selenium - selenium 如何识别是否有浏览器升级?
- python - 在 Python 中使用 requests 库从 Microsoft Academic Knowledge REST API 获取数据
- ios - React Native - 卡在启动屏幕 ios 模拟器上
- kubernetes - 共享文件作为 Kubernetes pod 之间的持久卷
- angular - 如何从 Angular 9 中的组件访问服务类中定义的变量?