我想列出目录中的所有图像来创建一个图库。下面的示例是为了获取目录路径。
我尝试过listFiles()方法,但它返回null。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Permision Request
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
1);
initialize();
}
//For the Intent to get Folder
private void initialize() {
Intent i = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
i.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(Intent.createChooser(i, "Choose directory"), 9999);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch(requestCode) {
case 9999:
//File myFile = new File(data.getData().toString());
String path = data.getData().toString();
//View the path
Log.i("Test", "Result URI " + path);
Toast.makeText(getApplicationContext(), "Result URI " +data.getData().toString(), Toast.LENGTH_LONG).show();
//Creating new File for the directory
File directory = new File(path);
File[] files = directory.listFiles();
Log.d("Files", "Size: "+ files.length);
for (int i = 0; i < files.length; i++)
{
//Show the name of the files in the directory
Log.d("Files", "FileName:" + files[i].getName());
}
break;
}
}在清单中,我还拥有读取外部存储的权限。
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />将返回目录中文件的de,但返回此错误:
Caused by: java.lang.NullPointerException: Attempt to get the length of null array
at cu.edu.cujae.citi.folderpicker.MainActivity.workWithFile(MainActivity.java:59)
at cu.edu.cujae.citi.folderpicker.MainActivity.onActivityResult(MainActivity.java:49)
at android.app.Activity.dispatchActivityResult(Activity.java:6932)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4085)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4132)
at android.app.ActivityThread.-wrap20(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1533)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)发布于 2019-06-26 17:03:25
下面的示例是为了获取目录路径。
不,它使用ACTION_OPEN_DOCUMENT_TREE来获取文档树。这可能表示也可能不表示文件系统上的目录。
使用ACTION_OPEN_DOCUMENT_TREE返回的ACTION_OPEN_DOCUMENT_TREE最简单的方法是使用DocumentFile.fromTreeUri()。然后,您可以在它上调用listFiles(),让DocumentFile对象指向该树中的文档(和子树)。
https://stackoverflow.com/questions/56777815
复制相似问题