我在我的应用程序上使用了 recyclerView 来显示来自外部存储的所有文件。在我更改它之前,它在“MainActivity.java”中实现时运行良好。
现在,我希望我的应用程序有一个“BottomNavigationBar”;为了做到这一点,我使用片段。问题是当我触摸菜单中的特定项目(包含 RecyclerView 的项目)时应用程序崩溃。
我将所有“this”方法更改为“.getActivity()”,但它还是崩溃了。我将其更改为“.getActivity().getApplicationContext()”,但它仍然崩溃。
对不起,我的电脑不支持硬件加速,所以我无法正确显示错误是什么。相反,我已将调试器连接到我连接的手机并设置断点。"RecyclerView recyclerView = getView().findViewById(R.id.recyclerview);"
当应用程序崩溃时,调试器会突出显示该行。
这是片段代码:
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_records, container, false);
}
private static final int PERMISSION_REQUEST = 1000;
private ArrayList<String> mNames = new ArrayList<>();
public static ArrayList<String> NbFiles = new ArrayList<>();
public ArrayList<String> PathFiles = new ArrayList<>();
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Check if we have the permission to read storage
if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
//We don't have the permission, so request it.
ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST);
}
//We already have permission
else {
permissionExists();
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PERMISSION_REQUEST) {
if (resultCode == RESULT_OK) {
permissionExists();
} else {
//handle error
}
}
}
private void initRecyclerView() {
RecyclerView recyclerView = getView().findViewById(R.id.recyclerview);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(mNames, getActivity().getApplicationContext(), (RecyclerViewAdapter.OnNoteListener) this);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));
}
private void permissionExists() {
String path = Environment.getExternalStorageDirectory().toString() + "/Rapture";
File directory = new File(path);
boolean success = true;
if (!directory.exists()) {
success = directory.mkdirs();
}
if (success) {
File[] arrayFiles = directory.listFiles();
for (File file : arrayFiles) {
mNames.add(file.getName());
PathFiles.add(file.getPath());
NbFiles.add(file.getName());
}
}
initRecyclerView();
}
}
[如果您需要更多代码,请告诉我]
我怎样才能解决这个问题 ?