我是Android的新手,正在尝试测试一些东西。 我有一个简单的应用程序,我只想从任何Android文件夹中读取文件。 到目前为止,我只是检查了路径,这是我从以下内容中了解到的。
context.getExternalFilesDir(null);
&
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
获得的路径类似于:
/storage/emulated/0/ then rest of the folders
我已经做了一切,包括在清单文件和应用程序中请求权限。我检查了权限是否被授予,文件夹路径也是正确的,但是File.listFiles()
仍然抛出空指针异常。
请查看下面的代码:
清单文件中的权限
<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
Service
或者Doze Mode
... 不管怎样,把问题发到 Stack Overflow 上,肯定会有人回答的... - Vishnu