java.lang.NullPointerException:尝试获取null数组的长度 - 尝试从gallery中获取所有照片并将它们放在Activity上

问题描述 投票:1回答:2

我的目标是创建一个应用程序,点击它后,将显示一个活动,电话库和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
2个回答
0
投票

根据文件

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。希望对你有效。

并且还要检查目录是否存在。


0
投票

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

如果我的设备中的路径ExternalStorageDirectoryPath + "/test/"不为null,则无论文件夹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/",所以在我们遍历文件夹中的图片之前它不是null。

© www.soinside.com 2019 - 2024. All rights reserved.