问题:
该代码用于从外部存储中选择一个文件以从 Android 应用程序进行 OTA 更新。这在 Kitkat 中运行良好,但在选择路径应用程序时,当涉及到 Nougat 手机(Moto G4)时会崩溃。
我尝试调试,问题是 在 Nougat 版本中file = new File(item.getFilePath());
创建的这条线NullPointerException
,我也尝试在 Manifest 中授予读取外部存储的权限,但问题仍然存在。可能是什么问题?我已经发布了下面的代码。请帮助
public class ChooseImageFileDialog extends Activity {
private FileListAdapter mAdaptor;
private ArrayList<FileFolderItem> mFileFolderList;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mChooseButton = (Button) findViewById(R.id.select_button);
mChooseButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mSelectedFile != null) {
getIntent().putExtra(RETURN_PATH_RESULT,
mSelectedFile.getPath());
setResult(RESULT_OK, getIntent());
finish();
}
}
});
mFileFolderList = new ArrayList<FileFolderItem>();
mAdaptor = new FileListAdapter(this, mFileFolderList);
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> listview, View view, int
position, long id) {
FileFolderItem item = mFileFolderList.get(position);
if (item == null)
return;
File file = new File(item.getFilePath());
highlightSelectedItem(listview, view);
}
});
修改:27/11/2017
mChooseButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mSelectedFile != null) {
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
Log.e("value", "Permission already Granted, Now you
can save image.");
}
else {
requestPermission();
}
}else {
Log.e("value", "Not required for requesting runtime
permission");
getIntent().putExtra(RETURN_PATH_RESULT,
mSelectedFile.getPath());
setResult(RESULT_OK, getIntent());
finish();
}
}
}
});
private boolean checkPermission() {
int result =
ActivityCompat.checkSelfPermission(ChooseImageFileDialog.this,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
}else{
return false;
}
}
private void requestPermission()
{
if(ActivityCompat.
shouldShowRequestPermissionRationale(ChooseImageFileDialog.th
is,Manifest.permission.WRITE_EXTERNAL_STORAGE))
{
Toast.makeText(ChooseImageFileDialog.this, "Write External Storage
permission allows us to do store images. Please allow this
permission in App Setting", Toast.LENGTH_LONG).show();
}
else
{
ActivityCompat.requestPermissions(ChooseImageFileDialog.this, new
String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
PERMISSION_REQUEST_CODE);
}
}
我也修改了代码以获取运行时权限,但应用程序仍然崩溃。仍然有同样的问题