使用imageView时出现空指针异常

时间:2013-12-22 23:09:01

标签: android nullpointerexception

我的GridViewAdapter类中有一个imageView:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Try to reuse the views
    ImageView view = (ImageView) convertView;
    boolean checked = (mCheckBox==null)?false:(((CheckBox)  mCheckBox).isChecked());
    // if convert view is null then create a new instance else reuse it
    if (view == null) {
        view = new ImageView(Context);
        view.setId(1);
        Log.d("GridViewAdapter", "new imageView added");
    }

然后我在这里尝试将位图设置为另一个类中的imageView(view):

@Override
                public void onClick(View v) {
                    if (addCheckbox.isChecked()) {
                        System.out.println("Checked");

                        PackageManager pm = mContext.getPackageManager();
                        final int   DEST_IMAGE_WIDTH = 100;
                        final int DEST_IMAGE_HEIGHT = 100;
                        ApplicationInfo appInfo = mContext.getApplicationInfo();
                        Drawable appIcon = pm.getApplicationIcon(appInfo);
                        Bitmap appBmp  = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888); 

                        // Creates a new canvas based on the image specification
                        // created just above.
                        Canvas canvas = new Canvas(appBmp);
                        // (optional) Fills the entire canvas
                        canvas.drawColor(Color.WHITE);
                        // You need to set bounds otherwise a 0,0 sized image would be drawn.
                        appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
                        appIcon.draw(canvas);

                        /// Let's save to a .jpg file ...
                        File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
                        FileOutputStream out;
                        try
                        {
                            file.createNewFile();
                            out = new FileOutputStream(file);
                            appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
                            out.close();

                            // Load back the image file to confirms it works
                          Bitmap bitmap = BitmapFactory.decodeFile( file.getAbsolutePath() );
                          ImageView imageView1 = (ImageView)v.findViewById(1);
                          imageView1.setImageBitmap( bitmap );            
                        }

但是我得到了这个NPE:

12-22 15:58:45.782: E/AndroidRuntime(28793): FATAL EXCEPTION: main
12-22 15:58:45.782: E/AndroidRuntime(28793): java.lang.NullPointerException
12-22 15:58:45.782: E/AndroidRuntime(28793):    at com.example.awesomefilebuilderwidget.AppInfoAdapter$1.onClick(AppInfoAdapter.java:200)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.view.View.performClick(View.java:2532)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.widget.CompoundButton.performClick(CompoundButton.java:99)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.view.View$PerformClick.run(View.java:9308)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.os.Handler.handleCallback(Handler.java:587)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.os.Handler.dispatchMessage  (Handler.java:92)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.os.Looper.loop(Looper.java:150)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at android.app.ActivityThread.main(ActivityThread.java:4333)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at java.lang.reflect.Method.invokeNative(Native Method)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at java.lang.reflect.Method.invoke(Method.java:507)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-22 15:58:45.782: E/AndroidRuntime(28793):    at dalvik.system.NativeStart.main(Native Method)

这是第200行:

imageView1.setImageBitmap( bitmap ); 

显然我的imageView正在返回null

我猜我没有正确设置ID和/或使用不正确?

如何解决此问题NPE

增加:

这是我的完整适配器类(GridViewAdapter):

    package com.example.awesomefilebuilderwidget;

    IMPORTS

    public class GridViewAdapter extends BaseAdapter {
    private Context Context;

    // Keep all Images in array list
    public ArrayList<Integer> drawables = new ArrayList<Integer>();

    CheckBox mCheckBox=null;

    // Constructor
    public GridViewAdapter(Context c){
        Context = c;
        Log.d("GridViewAdapter", "Constructor is set");

        drawables.add(R.drawable.pattern1);
        Log.d("GridViewAdapter", "pattern1 added");

        drawables.add(R.drawable.pattern2);
        Log.d("GridViewAdapter", "pattern2 added");

        drawables.add(R.drawable.trashcan);
        Log.d("GridViewAdapter", "trashcan added");

        drawables.add(R.drawable.ic_launcher);
        Log.d("GridViewAdapter", "ic_launcher added");
    }

    public void setCheckBox(CheckBox checkbox){
        mCheckBox=checkbox;
    }

    @Override
    // How many items are in the data set represented by this Adapter
    public int getCount() {
        return drawables.size();
    }

    @Override
    // Get the data item associated with the specified position in the
    // data set
    public Object getItem(int position) {
        return drawables.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public boolean isSdReadable() {

        boolean mExternalStorageAvailable = false;
        String state = Environment.getExternalStorageState();

        if (Environment.MEDIA_MOUNTED.equals(state)) {
        // We can read and write the media
        mExternalStorageAvailable = true;
        Log.i("isSdReadable", "External storage card is readable.");
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
        // We can only read the media
        Log.i("isSdReadable", "External storage card is readable.");
        mExternalStorageAvailable = true;
        } else {
        // Something else is wrong. It may be one of many other
        // states, but all we need to know is we can neither read nor write
        mExternalStorageAvailable = false;
        }

        return mExternalStorageAvailable;
        }

    public Bitmap getThumbnail() {

        final String APP_PATH_SD_CARD = "/TEST/";
        final String APP_THUMBNAIL_PATH_SD_CARD = "thumbnails";
        String filename = "AFBWIcon.png";

        String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;
        Bitmap thumbnail = null;

        // Look for the file on the external storage
        try {
        if (isSdReadable() == true) {
        thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
        }
        } catch (Exception e) {
        Log.e("getThumbnail() on external storage", e.getMessage());
        }

        // If no file on external storage, look in internal storage
        if (thumbnail == null) {
        try {
        File filePath = Context.getFileStreamPath(filename);
        FileInputStream fi = new FileInputStream(filePath);
        thumbnail = BitmapFactory.decodeStream(fi);
        } catch (Exception ex) {
        Log.e("getThumbnail() on internal storage", ex.getMessage());
        }
        }
        return thumbnail;
        }



    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // Try to reuse the views
        ImageView view = (ImageView) convertView;
        boolean checked = (mCheckBox==null)?false:(((CheckBox)  mCheckBox).isChecked());
        // if convert view is null then create a new instance else reuse it
        if (view == null) {
            view = new ImageView(Context);
            //view.setTag(ViewId(), "imageViewGRID");
            view.setId(1);
            Log.d("GridViewAdapter", "new imageView added");
        }
        if(checked == true){
            isSdReadable();
            Log.i("GridViewAdapter", "checkbox is checked");
        } else {
            Log.i("GridView", "Icons not for use/checkbox not checked");
        }
        view.setImageResource(drawables.get(position));
        view.setScaleType(ImageView.ScaleType.CENTER_CROP);
        view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
        view.setTag(String.valueOf(position));
        return view;
    }

}

1 个答案:

答案 0 :(得分:0)

ImageView imageView1 = (ImageView)v.findViewById(1);

这是怎么回事? 你不应该有这样的东西让它起作用:

ImageView imageView1 = (ImageView)v.findViewById(R.id.example);

您需要为findViewById

提供id而不是整数