【问题标题】:java.lang.NullPointerException: Attempt to get length of null array - when trying to take all the photos from gallery and place them on an Activityjava.lang.NullPointerException:尝试获取空数组的长度 - 尝试从图库中获取所有照片并将它们放在 Activity 上时
【发布时间】:2015-10-20 08:04:17
【问题描述】:

我的目标是创建一个应用程序,单击它后,将显示一个活动,并将手机图库和 SD 卡中的所有照片放在此活动上。不幸的是,我有一个我无法找到的错误。下面我发布我的 .java 文件和错误日志。

package com.example.androidgridview;

import java.io.File;
import java.util.ArrayList;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {

    public class ImageAdapter extends BaseAdapter {

        private Context mContext;
        ArrayList<String> itemList = new ArrayList<String>();

        public ImageAdapter(Context c) {
            mContext = c;   
        }

        void add(String path){
            itemList.add(path); 
        }

        @Override
        public int getCount() {
            return itemList.size();
        }

        @Override
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return null;
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(8, 8, 8, 8);
            } else {
                imageView = (ImageView) convertView;
            }

            Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);

            imageView.setImageBitmap(bm);
            return imageView;
        }

        public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {

            Bitmap bm = null;
            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path, options);

            // Calculate inSampleSize
            options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

            // Decode bitmap with inSampleSize set
            options.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(path, options); 

            return bm;      
        }

        public int calculateInSampleSize(

            BitmapFactory.Options options, int reqWidth, int reqHeight) {
            // Raw height and width of image
            final int height = options.outHeight;
            final int width = options.outWidth;
            int inSampleSize = 1;

            if (height > reqHeight || width > reqWidth) {
                if (width > height) {
                    inSampleSize = Math.round((float)height / (float)reqHeight);    
                } else {
                    inSampleSize = Math.round((float)width / (float)reqWidth);      
                }   
            }

            return inSampleSize;    
        }

    }

    ImageAdapter myImageAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        GridView gridview = (GridView) findViewById(R.id.gridview);
        myImageAdapter = new ImageAdapter(this);
        gridview.setAdapter(myImageAdapter);

        String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory()
                .getAbsolutePath();

        String targetPath = ExternalStorageDirectoryPath + "/test/";

        Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
        File targetDirector = new File(targetPath);

        File[] files = targetDirector.listFiles();
        for (File file : files){
            myImageAdapter.add(file.getAbsolutePath());
        } 
    }
}

这是错误日志:

      java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidgridview/com.example.androidgridview.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2694)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2759)
            at android.app.ActivityThread.access$900(ActivityThread.java:178)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:145)
            at android.app.ActivityThread.main(ActivityThread.java:5944)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
            at com.example.androidgridview.MainActivity.onCreate(MainActivity.java:129)
            at android.app.Activity.performCreate(Activity.java:6289)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2647)
           

【问题讨论】:

标签: android gallery photos


【解决方案1】:

根据文档

listFiles 返回包含在此文件表示的目录中的文件数组。如果此文件不是目录,则结果为 null。

File[] files = targetDirector.listFiles(); 
    if(files!=null){
                for (File file : files){
                    myImageAdapter.add(file.getAbsolutePath());
                } 
            }else{
                // do something if directory is null 
            }

添加对 null 的检查。因为 listfiles 返回一个文件数组或 null。 希望它对你有用。

并添加检查目录是否存在。

【讨论】:

    【解决方案2】:

    我已经运行了你上面粘贴的代码,我发现你的目标路径是ExternalStorageDirectoryPath + "/test/";

    如果我的设备中的路径ExternalStorageDirectoryPath + "/test/"不为空,那么无论ExternalStorageDirectoryPath + "/test/"文件夹是否有图片,代码都可以正常工作。但是如果ExternalStorageDirectoryPath + "/test/"的路径为null,则for (File file : files){行会出现NullPointerException错误。

    所以我们可以这样尝试:如果路径是 null ,我们创建路径来避免这个错误。我的改变是:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        GridView gridview = (GridView) findViewById(R.id.gridview);
        myImageAdapter = new ImageAdapter(this);
        gridview.setAdapter(myImageAdapter);
    
        String ExternalStorageDirectoryPath = Environment
                .getExternalStorageDirectory()
                .getAbsolutePath();
    
        String targetPath = ExternalStorageDirectoryPath + "/test/";
        System.err.println(isFolderExists(targetPath));
    
        Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG).show();
        File targetDirector = new File(targetPath);
    
        File[] files = targetDirector.listFiles();
        for (File file : files){
            myImageAdapter.add(file.getAbsolutePath());
        } 
    }
    
    private boolean isFolderExists(String strFolder) {
        File file = new File(strFolder);        
        if (!file.exists()) {
            if (file.mkdirs()) {                
                return true;
            } else {
                return false;
    
            }
        }
        return true;
    }
    

    我调用了 isFolderExists() 方法来创建路径ExternalStorageDirectoryPath + "/test/",所以在我们遍历文件夹中的图片之前它不为空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多