Android - getView() - TextView空指针异常

时间:2013-07-22 19:54:36

标签: android nullpointerexception textview

我在自定义Adapter的getView()方法中有一个TextView引用,如下所示:

final TextView favs = (TextView) convertView.findViewById(R.id.nofavs);

这很好,但是,当我尝试在下一行中立即设置其文本时,我收到NullPointerException错误:

final TextView favs = (TextView) convertView.findViewById(R.id.favs);
favs.setText("3 favourites");

编辑: LogCat

07-22 21:07:52.815: E/AndroidRuntime(31514): FATAL EXCEPTION: main
07-22 21:07:52.815: E/AndroidRuntime(31514): java.lang.NullPointerException
07-22 21:07:52.815: E/AndroidRuntime(31514):    at com.guide.Tab01_FavAdapter.getView(Tab01_FavAdapter.java:65)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.AbsListView.obtainView(AbsListView.java:2461)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.GridView.onMeasure(GridView.java:1030)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.view.View.measure(View.java:15473)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5056)
07-22 21:07:52.815: E/AndroidRuntime(31514):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
...

2 个答案:

答案 0 :(得分:0)

你应该先检查转换视图是否为空,如果它为null,则会使视图膨胀...

if(convertView == null) {
  LayoutInflater inflater = getLayoutInflater();
  convertView = inflater.inflate(R.layout.row, parent, false);
}

阅读此getView(...)

答案 1 :(得分:-1)

你应该使用nofavs.setText("3 facourites"),因为变量的名称是nofavs。