程序files.length为null后崩溃怎么办

来源:爱站网时间:2022-01-18编辑:网友分享
今天爱站技术频道小编给大家详细说说程序files.length为null后崩溃怎么办的解决思路,感兴趣的小伙伴可以来看一看。希望这篇文章能帮助到各位朋友解决问题。

问题描述


我在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 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 

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

思路:


为了访问文件,必须在清单文件中提供权限。

尝试一下:

checkPermissionReadStorage(this);
String path = Environment.getExternalStorageDirectory().toString()+"/Android";
Log.d("Files", "Path: " + path);
File directory = new File(path);
File[] files = directory.listFiles();
if (files != null)
{
   Log.d("Files", "Size: "+ files.length);
   for (int i = 0; i 

将此方法添加到您的类中,我遇到了与您所说的相同的崩溃,但是添加此方法后,我得到了正确的结果-

D /文件:FileName:数据

public static void checkPermissionReadStorage(Activity activity) {
        if (ContextCompat.checkSelfPermission(activity,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            if (!ActivityCompat.shouldShowRequestPermissionRationale(activity,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {
                ActivityCompat.requestPermissions(activity,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        1);
            }
        }
    }

以上就是小编所要带给大家关于JAVA编程的相关内容了,不知道朋友们对程序files.length为null后崩溃怎么办的内容了解清楚了没有,还不明白可以给小编留言。

 

上一篇:JavaFx项目出现异常后怎么解决

下一篇:现有的JDK怎么在系统上查找

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载