尝试查找空数组的长度,但数组包含多个文件名

时间:2018-02-11 13:24:30

标签: java android file nullpointerexception android-external-storage

我试图获取包含文件夹内文件的数组的长度,但是它说数组为空。

 @Override
    public void onItemClick(View view, int position) {
        String string1 = adapter.getItem(position);
        String path = Environment.getExternalStorageDirectory().getAbsolutePath()+ string1;
        File directory = new File(path);
        File[] files = directory.listFiles();
        Toast.makeText(this, Integer.toString(files.length), Toast.LENGTH_SHORT)  //this line throws NPE exception
            .show();
    }

当我用{替换String path1 = Environment.getExternalStorageDirectory().getAbsolutePath()+ string1;时,它工作正常  String path1 = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/Pictures";

包含getItem方法的适配器:

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private ArrayList<String> mData;
    private ArrayList<String> mData2;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;
    private Context context;

    // data is passed into the constructor
    public MyRecyclerViewAdapter(Context context, ArrayList<String> data, ArrayList<String> data2) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
        this.mData2 = data2;
        this.context = context;
    }

 // inflates the cell layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_item, parent, false);
        return new ViewHolder(view);
    }

  // binds the data to the textview in each cell
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        String animal2 = mData2.get(position);
        int THUMBSIZE = 100;
        Bitmap ThumbImage = ThumbnailUtils.extractThumbnail(BitmapFactory.decodeFile(animal2),
                THUMBSIZE, THUMBSIZE);
        Bitmap thumb = ThumbnailUtils.createVideoThumbnail(animal2, MediaStore.Video.Thumbnails.MINI_KIND);
        holder.myTextView.setText(animal);
            if(animal!= null && animal.endsWith(".mp3")){
                holder.myImage.setImageResource(R.drawable.song);
            }
        else if(animal!= null && animal.endsWith(".pdf")){
            holder.myImage.setImageResource(R.drawable.pdficon2);
        }
        else
            if(animal!= null && animal.endsWith(".jpeg") && BitmapFactory.decodeFile(animal2)!=null ){
                holder.myImage.setImageBitmap(ThumbImage);
            }
            else
            if(animal!= null && animal.endsWith(".mp4")){
                holder.myImage.setImageBitmap(thumb);
            }
            else
            if(animal!= null && animal.endsWith(".zip")){
                holder.myImage.setImageResource(R.drawable.zip);
            }
            else
            if(animal!= null && animal.endsWith(".aac")){
                holder.myImage.setImageResource(R.drawable.song);
            }
            else
            if(animal!= null && animal.endsWith(".txt")){
                holder.myImage.setImageResource(R.drawable.text);
            }
           else if(animal!= null && animal.endsWith(".apk")){
            PackageInfo packageInfo = context.getPackageManager()
                    .getPackageArchiveInfo(animal2, PackageManager.GET_ACTIVITIES);
            if(packageInfo != null) {
                ApplicationInfo appInfo = packageInfo.applicationInfo;
                    appInfo.sourceDir = animal2;
                    appInfo.publicSourceDir = animal2;
                Drawable icon = appInfo.loadIcon(context.getPackageManager());
                Bitmap bmpIcon = ((BitmapDrawable) icon).getBitmap();
                holder.myImage.setImageBitmap(bmpIcon);
            }

        }
            else {
                holder.myImage.setImageResource(R.drawable.folder);
            }
        }

// total number of cells
    @Override
    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;
        ImageButton myImage;
        ViewHolder(View itemView) {
            super(itemView);
            myImage = (ImageButton) itemView.findViewById(R.id.buttonimage);
            myTextView = (TextView) itemView.findViewById(R.id.info_text);
            myImage.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

 public String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught
    public void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

LOGCAT:

 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                         Process: com.example.dell_1.Myapp3, PID: 3755
                                                                         java.lang.NullPointerException: Attempt to get length of null array
                                                                             at com.example.dell_1.myapp3.InternalStorage.onItemClick(InternalStorage.java:43)
                                                                             at com.example.dell_1.myapp3.MyRecyclerViewAdapter$ViewHolder.onClick(MyRecyclerViewAdapter.java:120)
                                                                             at android.view.View.performClick(View.java:5609)
                                                                             at android.view.View$PerformClick.run(View.java:22263)
                                                                             at android.os.Handler.handleCallback(Handler.java:751)
                                                                             at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                             at android.os.Looper.loop(Looper.java:154)
                                                                             at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                                             at java.lang.reflect.Method.invoke(Native Method)
                                                                             at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                                             at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

清单文件包含以下权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WRITE_MEDIA_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.MEDIA_CONTENT_CONTROL" />

另外,我也在运行时要求权限。

private void buttonClicked(View view) {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE) + ContextCompat
                .checkSelfPermission(this,
                        Manifest.permission.INTERNET)
                != PackageManager.PERMISSION_GRANTED) {

            Snackbar.make(view, "Permission not Granted, Requesting permission.", Snackbar.LENGTH_LONG).show();
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE)) {

                Snackbar.make(view, "We need permission to internal storage for displaying songs", Snackbar.LENGTH_LONG).show();

            } else {

                Snackbar.make(view, "Allow myapp3 to access this device's internal storage", Snackbar.LENGTH_LONG).show();

                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                        MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);

                // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
                // app-defined int constant. The callback method gets the
                // result of the request.
            }
        }
    }


 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS granted", Toast.LENGTH_SHORT)
                            .show();


                } else {

                    Toast.makeText(Bacon1.this, "WRITE_CONTACTS Denied", Toast.LENGTH_SHORT)
                            .show();

                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

2 个答案:

答案 0 :(得分:1)

您可能需要文件的绝对路径。所以,改为使用:

String path = Environment.getExternalStorageDirectory().toString() + string1;

尝试使用:

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + string1;

答案 1 :(得分:0)

在清单中添加此权限以读取文件夹内容,否则将返回null:

DateTimeFormatter

你的文件夹无论如何都是空的,所以检查DateTimeFormatter timeFormatter = DateTimeFormatter .ofLocalizedTime(FormatStyle.FULL) .withZone(ZoneId.systemDefault()); LocalTime time = LocalTime.of(12, 45, 0); System.out.println(timeFormatter.format(time)); 是否也是一个好习惯:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />