У меня есть этот класс активности в onCreate. Я проверяю, существует ли файл, или нет. Я написал код для запроса разрешений для внешнего чтения, я даже добавил разрешения в манифест, но код в onCreate падает Приложение сообщает, что files.length имеет значение null. После предоставления пользователю разрешения происходит сбой приложения, поскольку выполняется код для получения списка файлов.
package com.example.instantshare.UI.Activities;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.instantshare.R;
import com.example.instantshare.UI.Helpers.FileExplorerHelper;
import com.example.instantshare.UI.Models.FileItem;
import com.example.instantshare.UI.UIComponents.FileListRecyclerViewAdapter;
import com.faraji.environment3.Device;
import com.faraji.environment3.Environment3;
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
public class FilePickerActivity extends AppCompatActivity {
private static final String TAG = "FilePickerActivity";
private final int REQUEST_CODE = 1;
private static final ArrayList<FileItem> list = new ArrayList<>();
private static Context context;
// View variables
static RecyclerView fileListRecyclerView;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_picker);
init();
final String rawExternalStorage = System.getenv("EXTERNAL_STORAGE");
File file = new File("/sdcard/Android");
Log.d(TAG, "onCreate: " + file.isDirectory() + " " + file.exists());
File[] files = file.listFiles();
Log.d(TAG, "onCreate: " + files.length);
}
private void init(){
fileListRecyclerView = findViewById(R.id.file_list_recycler_view);
context = FilePickerActivity.this;
if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this,Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},REQUEST_CODE);
}
else{
readFileInit();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case REQUEST_CODE:
{
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
readFileInit();
}
else{
finish();
}
}
}
}
private void readFileInit(){
FileItem internalStorage = new FileItem("Internal Storage","","internal_storage","internal_storage", Environment.getExternalStorageDirectory().getAbsolutePath(),"",true,false,false);
list.add(internalStorage);
try {
File storage = Environment3.getSecondaryExternalStorage().getFile();
FileItem externalStorage = new FileItem(storage.getName(),"","external_storage","external_storage", storage.getAbsolutePath(),"",true,false,false);
Log.d(TAG, "readFileInit: " + externalStorage.getPath());
list.add(externalStorage);
}
catch (Exception e){
e.printStackTrace();
}
FileListRecyclerViewAdapter fileListRecyclerViewAdapter = new FileListRecyclerViewAdapter(this,list);
fileListRecyclerView.setLayoutManager(new LinearLayoutManager(this));
fileListRecyclerView.setAdapter(fileListRecyclerViewAdapter);
}
public static void clickedItem(FileItem fileItem){
if (fileItem.getStorage() ){
File directory = new File(fileItem.getPath());
File[] files = directory.listFiles();
Log.d(TAG, "clickedItem: " + files.length);
for(int i = 0; i < files.length; i++){
FileItem list_item = new FileItem();
File file = files[i];
list_item.setName(file.getName());
list_item.setDirectory(file.isDirectory());
list_item.setFile(file.isFile());
list_item.setStorage(false);
list_item.setLastModified(new Date(file.lastModified()).toString());
list_item.setPath(file.getAbsolutePath());
list_item.setExtension(file.getName().split(".")[1]);
list_item.setType(getFileType());
list.add(list_item);
}
FileListRecyclerViewAdapter fileListRecyclerViewAdapter = new FileListRecyclerViewAdapter(context,list);
fileListRecyclerView.setAdapter(fileListRecyclerViewAdapter);
}
else if(fileItem.getDirectory()){
File directory = new File(fileItem.getPath());
File[] files = directory.listFiles();
for(int i = 0; i < files.length; i++){
FileItem list_item = new FileItem();
File file = files[i];
list_item.setName(file.getName());
list_item.setDirectory(file.isDirectory());
list_item.setFile(file.isFile());
list_item.setStorage(false);
list_item.setLastModified(new Date(file.lastModified()).toString());
list_item.setPath(file.getAbsolutePath());
list_item.setExtension(file.getName().split(".")[1]);
list_item.setType(getFileType());
list.add(list_item);
}
FileListRecyclerViewAdapter fileListRecyclerViewAdapter = new FileListRecyclerViewAdapter(context,list);
fileListRecyclerView.setAdapter(fileListRecyclerViewAdapter);
}
else{
return;
}
}
private static String getFileType(){
return "";
}
}
Stacktrace
2020-02-24 20:39:33.934 10270-10270/com.example.instantshare D/FilePickerActivity: onCreate: true true
2020-02-24 20:39:33.936 10270-10270/com.example.instantshare D/AndroidRuntime: Shutting down VM
2020-02-24 20:39:33.944 10270-10270/com.example.instantshare E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.instantshare, PID: 10270
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.instantshare/com.example.instantshare.UI.Activities.FilePickerActivity}: java.lang.NullPointerException: Attempt to get length of null array
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3344)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3488)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2049)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7506)
at java.lang.reflect.Method.invoke(Native Method)
at com.an
2020-02-24 20:39:34.060 10270-10270/com.example.instantshare I/Process: Sending signal. PID: 10270 SIG: 9