如何在android中处理空指针异常

时间:2012-09-03 11:18:34

标签: android

我正在尝试制作照片库应用程序。但是我有以下错误,我的程序将崩溃。我也遇到错误:

imageView.setImageResource(pics[arg2]);

错误

09-03 16:45:22.618: E/AndroidRuntime(443): Uncaught handler: thread main exiting due to uncaught exception
09-03 16:45:22.628: E/AndroidRuntime(443): java.lang.NullPointerException
09-03 16:45:22.628: E/AndroidRuntime(443):  at com.example.myfirstapplication.setwall$1.onItemClick(setwall.java:40)
09-03 16:45:22.648: E/dalvikvm(443): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

这是我的代码:

package com.sai.samples.views;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class GalleryView extends Activity {
    Integer[] pics = {
            R.drawable.antartica1,
            R.drawable.antartica2,
            R.drawable.antartica3,
            R.drawable.antartica4,
            R.drawable.antartica5,
            R.drawable.antartica6,
            R.drawable.antartica7,
            R.drawable.antartica8,
            R.drawable.antartica9,
            R.drawable.antartica10
    };
    ImageView imageView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Gallery ga = (Gallery)findViewById(R.id.Gallery01);
        ga.setAdapter(new ImageAdapter(this));

        imageView = (ImageView)findViewById(R.id.ImageView01);
        ga.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                Toast.makeText(getBaseContext(), 
                        "You have selected picture " + (arg2+1) + " of Antartica", 
                        Toast.LENGTH_SHORT).show();
                imageView.setImageResource(pics[arg2]);

            }

        });

    }


    public class ImageAdapter extends BaseAdapter {

        private Context ctx;
        int imageBackground;

        public ImageAdapter(Context c) {
            ctx = c;
            TypedArray ta = obtainStyledAttributes(R.styleable.Gallery1);
            imageBackground = ta.getResourceId(R.styleable.Gallery1_android_galleryItemBackground, 1);
            ta.recycle();
        }

        @Override
        public int getCount() {

            return pics.length;
        }

        @Override
        public Object getItem(int arg0) {

            return arg0;
        }

        @Override
        public long getItemId(int arg0) {

            return arg0;
        }

        @Override
        public View getView(int arg0, View arg1, ViewGroup arg2) {
            ImageView iv = new ImageView(ctx);
            iv.setImageResource(pics[arg0]);
            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(new Gallery.LayoutParams(150,120));
            iv.setBackgroundResource(imageBackground);
            return iv;
        }

    }
}

这是我的main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<Gallery 
    android:id="@+id/Gallery01" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"></Gallery>
<ImageView 
    android:id="@+id/ImageView01" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"></ImageView>

</LinearLayout>

3 个答案:

答案 0 :(得分:7)

这一行可能会返回null:

imageView = (ImageView)findViewById(R.id.ImageView01);

检查ImageView ID是否正确,如果错误仍然存​​在,请尝试清理并重建项目。

答案 1 :(得分:1)

我已经使用此代码创建了一个图库,

public class GalleryViewActivity extends Activity 
{

    GridView gridView;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gridView = (GridView)findViewById(R.id.gridView);

           gridView.setAdapter(new ImageAdapter(this));
    }
}


class ImageAdapter extends BaseAdapter 
{
    ArrayList<String> images;

    private Context mContext;

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

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final 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(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        }
        else 
        {
            imageView = (ImageView) convertView;
        }
           imageView.setClickable(true);

           imageView.setOnClickListener(new OnClickListener()
           {            
            @Override
            public void onClick(View v) 
            {
                Intent i = new Intent(v.getContext(), showImageClass.class);
                Toast.makeText(v.getContext(), mThumbIds.toString() + " Clicked", 5000).show();
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra("imageName", mThumbIds[position]);
                v.getContext().startActivity(i);
            }
        });
//         imageView.setImageDrawable(images);
//         imageView.setImageBitmap(images);
//         imageView.setImageResource(images[]);
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

//     references to images
    private Integer[] mThumbIds = 
    {
            R.drawable.abc,
            R.drawable.def,
            R.drawable.klm, 
            R.drawable.pqr,
            R.drawable.rst, 
            R.drawable.wxy,
            R.drawable.xyz, 
    };
}

答案 2 :(得分:1)

首先创建一个GalleryViewActivity类

public class GalleryViewActivity extends Activity 
{

    GridView gridView;
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        gridView = (GridView)findViewById(R.id.gridView);
        gridView.setAdapter(new ImageAdapter(this));
    }
}


class ImageAdapter extends BaseAdapter 
{
    ArrayList<String> images;

    private Context mContext;

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

    public int getCount() 
    {
        return mThumbIds.length;
    }

    public Object getItem(int position) 
    {
        return null;
    }

    public long getItemId(int position) 
    {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(final 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(85, 85));
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(8, 8, 8, 8);
        }
        else 
        {
            imageView = (ImageView) convertView;
        }
           imageView.setClickable(true);

           imageView.setOnClickListener(new OnClickListener()
           {            
            @Override
            public void onClick(View v) 
            {
                Intent i = new Intent(v.getContext(), showImageClass.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.putExtra("position", "" + position);
                v.getContext().startActivity(i);
            }
        });
        imageView.setImageResource(mThumbIds[position]);
        return imageView;
    }

//     references to images
    private Integer[] mThumbIds = 
    {
            R.drawable.abc,
            R.drawable.def,
            R.drawable.klm, 
            R.drawable.pqr,
            R.drawable.rst, 
            R.drawable.wxy,
            R.drawable.xyz, 
    };
}

别忘了在drawable文件夹中添加图片。图像应该与你在mThumbIds数组中提到的相同,就像我使用过abc.jpg,def.jpg等等。 然后你需要创建一个showImage.java类,在这里你可以使用一个imageview来显示点击图像的大视图。

public class showImageClass extends Activity
{
    private Integer[] mThumbIds = 
    {
            R.drawable.abc,
            R.drawable.def,
            R.drawable.klm, 
            R.drawable.pqr,
            R.drawable.rst, 
            R.drawable.wxy,
            R.drawable.xyz, 
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.showimage);
        int position = Integer.parseInt(this.getIntent().getStringExtra("position"));
        ImageView jpgView = (ImageView)findViewById(R.id.imageView);
        jpgView.setImageResource(mThumbIds[position]);
    }
}

此代码对我有用,肯定会有效.. 别忘了添加相关图像并导入所需的类库。 提及android清单文件中的活动