使用Android GridView时出现如下报错:
FATAL EXCEPTION: main
Process: aspectj.lhxtest2, PID: 25329
java.lang.RuntimeException: Unable to start activity ComponentInfo{aspectj.lhxtest2/aspectj.lhxtest2.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void aspectj.lhxtest2.GridView.MyGridView.setAdapter(android.widget.ListAdapter)’ on a null object reference at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2534)
本来以为是布局文件没有读到为空,实际上是因为第一步并不是得到控件。而是得到对象才可调用方法。
源文件报错代码:
MyGridView goodsGridView = (MyGridView) findViewById(R.id.single_choice_view_goods);
final GridViewAdapter mAdapter = new GridViewAdapter(this);
mAdapter.setData(goods,2);
goodsGridView.setAdapter(mAdapter);
这里DeBug显示的是goodsGridView为空;
这里需要把布局文件转化为视图对象,才能调用
修改代码如下:
LayoutInflater inflater = LayoutInflater.from(this);
View view01 = inflater.inflate(R.layout.activity_gridview, null);
MyGridView goodsGridView = (MyGridView)view01.findViewById(R.id.single_choice_view_goods);
final GridViewAdapter mAdapter = new GridViewAdapter(this);
mAdapter.setData(goods,2);