只需通過一個GridView設置適配器做一個簡單的練習:的Android這個(上下文)給NullPointerException異常
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
ImageAdapter是另一個類,如下:
public class ImageAdapter extends BaseAdapter {
// ---the images to display---
public Integer[] imageIDs = { R.drawable.one, R.drawable.two,
R.drawable.three, R.drawable.four, R.drawable.five,
R.drawable.six };
private Context context;
public ImageAdapter(Context c) {
context = c;
}
// ---returns the number of images---
public int getCount() {
return imageIDs.length;
}
// ---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// ---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(185, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 20, 5, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(imageIDs[position]);
return imageView;
}
}
當我調試代碼時,appview在gridview.setAdapter行崩潰,並報告java.lang.NullPointerException on 這個。任何想法如何可以克服?
感謝您的幫助球員,但我實際上發現了這個問題。該清單中沒有正確列出該活動。因此,我認爲,由於這個原因,活動的背景變得無效。 – Colin