Android Studio gridview.setAdapter(...)继续在Create

时间:2018-07-03 17:21:00

标签: android gridview nullpointerexception

我的问题是,我该怎么办才能解决此NullPointerException?我知道这意味着什么,但我不知道为什么会导致它。我找不到“空对象引用”,大部分代码取自:Android Develeopers GridView

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.pierpaolopascarella.schoolappv3, PID: 5174
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pierpaolopascarella.schoolappv3/com.example.pierpaolopascarella.schoolappv3.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference                                 
               Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference

MainActivity-onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    GridView gridview = (GridView) findViewById(R.id.grid);
    gridview.setAdapter(new GridAdapter(this)); //This line throws NullPointerException

GridAdapter类:

public class GridAdapter extends BaseAdapter {
private Context context;
public GridAdapter(Context c) {
    context = 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(int position, View convertView, ViewGroup parent) {
    ImageView imageView;

    if (convertView == null) {
        // if it's not recycled, initialize some attributes
        imageView = new ImageView(context);
        imageView.setLayoutParams(new ViewGroup.LayoutParams(85, 85));
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        imageView.setPadding(8, 8, 8, 8);
    } else {
        imageView = (ImageView) convertView;
        Log.i("rip", "!= null" );
    }

    imageView.setImageResource(mThumbIds[position]);
    return imageView;
}
int [] mThumbIds = {
        R.drawable.lente,
        R.drawable.lentelammetje,
        R.drawable.lente,
        R.drawable.pauwvliegen,
        R.drawable.rainbow,
        R.drawable.schatkamer,
        R.drawable.zomer,
        R.drawable.map,
        R.drawable.mic,
        R.drawable.pauw,
        R.drawable.settings
};
}

0 个答案:

没有答案