Android java.lang.NullPointerException:尝试获取空数组的长度-当尝试从gallery拍摄所有照片并将其放置在活动中时

Android java.lang.NullPointerException:尝试获取空数组的长度-当尝试从gallery拍摄所有照片并将其放置在活动中时,android,gallery,photos,Android,Gallery,Photos,我的目标是创建一个应用程序,单击该应用程序后,将显示一个活动,并且手机图库和SD卡中的所有照片都将放在该活动上。不幸的是,我有一个无法定位的错误。下面是我的.java文件和错误日志。 package com.example.androidgridview; import java.io.File; import java.util.ArrayList; import android.os.Bundle; import android.os.Environment; import androi

我的目标是创建一个应用程序,单击该应用程序后,将显示一个活动,并且手机图库和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());
        } 
    }
}

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

如果我的设备中的路径
ExternalStorageDirectoryPath+“/test/”
不为空,则无论文件夹
ExternalStorageDirectoryPath+“/test/”
是否有图片,代码都可以正常工作。但是,如果路径
ExternalStorageDirectoryPath+“/test/”
为空,则(File:files){
的行
中将发生NullPointerException错误

因此,我们可以这样尝试:如果路径为空,则创建路径以避免此错误。我的更改是:

@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/”
,这样在遍历文件夹中的图片之前它就不会为空。

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

如果我的设备中的路径
ExternalStorageDirectoryPath+“/test/”
不为空,则无论文件夹
ExternalStorageDirectoryPath+“/test/”
是否有图片,代码都可以正常工作。但是,如果路径
ExternalStorageDirectoryPath+“/test/”
为空,将在(文件:files){
的行
中发生NullPointerException错误

因此,我们可以这样尝试:如果路径为空,则创建路径以避免此错误。我的更改是:

@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/”
,这样在遍历文件夹中的图片之前它就不会为空。

根据文档

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

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


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

根据文档

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

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


还可以添加一个检查目录是否存在。

通过
font size
惊人,我喜欢你的幽默,你的目标非常大:)通过
font size
惊人,我喜欢你的幽默,你的目标非常大:)可能重复