【发布时间】:2020-07-26 10:33:57
【问题描述】:
我是 android 新手,正在尝试测试一些东西。我有这个简单的应用程序,我只想从任何 android 文件夹中读取文件。到现在为止,我只是检查了我从以下了解到的路径是如何存在的
context.getExternalFilesDir(null);
&
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
得到的路径是这样的
/storage/emulated/0/ then rest of the folders
我已经完成了所有工作,并在清单文件和应用程序中请求了许可。我检查即使授予了权限并且文件夹路径也正确,但 File.listFiles() 给了我空指针异常。
请看下面的代码:
manfest 文件中的权限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
获取权限并尝试检查文件的代码
if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},101);
Toast.makeText(getApplicationContext(),
"No permission yet",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),
"Permission already granted",
Toast.LENGTH_SHORT).show();
File dcimPath = new File("/storage/emulated/0/bluetooth"); //This path is correct
File[] files = dcimPath.listFiles(); // gives null pointer exception
Log.i("files length ",files.length+"");
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 101){
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
Toast.makeText(getApplicationContext(),
"Permission granted",
Toast.LENGTH_SHORT).show();
File dcimPath = new File("/storage/emulated/0/bluetooth/");
File[] files = dcimPath.listFiles(); //gives error
Log.i("files length ",files.length+"");
}
else{
Toast.makeText(getApplicationContext(),
"Permission denied",
Toast.LENGTH_SHORT).show();
}
}
}
错误
Caused by: java.lang.NullPointerException: Attempt to get length of null array
【问题讨论】:
标签: java android android-studio android-file