这已经在堆栈溢出时被问过很多次,我已经尝试了很多,但是当我在自定义适配器中的 TextView 上调用 setText 方法时,我仍然得到空指针异常。我必须显示所有收件箱消息,其中第一个 textview 显示发件人的号码,第二个 textView 显示短信。这是我的适配器:
public class MyArrayAdapter extends ArrayAdapter<Sms> {
private final Context context;
private final List<Sms> msgs;
private LayoutInflater inflater;
public MyArrayAdapter(Context context, List<Sms> msgs) {
super(context, R.layout.list_item, msgs);
this.context = context;
this.msgs = msgs;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
Sms s = getItem(position);
View vi = convertView;
ViewHolder vh = new ViewHolder();
if (vi == null) {
vi = getLayoutInflater().inflate(R.layout.list_item, parent, false);
vh.number = (TextView) findViewById(R.id.number);
vh.msg = (TextView) findViewById(R.id.sms);
vi.setTag(vh);
}
try{
vh.number.setText(s.getReadState());
vh.msg.setText(s.getMsg());
}
catch (NullPointerException e){
e.printStackTrace();
}
return vi;
}
}
public static class ViewHolder{
TextView number;
TextView msg;
}
请查看我的代码并告诉我哪里出错了。如果需要代码/xml 的任何其他部分,我会告诉你。我现在已经花了很多时间。
编辑:这是logcat
java.lang.NullPointerException
at com.gitanshu.smsiknow.MainActivity$MyArrayAdapter.getView(MainActivity.java:79)
at android.widget.AbsListView.obtainView(AbsListView.java:2143)
at android.widget.ListView.makeAndAddView(ListView.java:1831)
at android.widget.ListView.fillDown(ListView.java:674)
at android.widget.ListView.correctTooLow(ListView.java:1450)
at android.widget.ListView.fillGap(ListView.java:648)
at android.widget.AbsListView.trackMotionScroll(AbsListView.java:4930)
at android.widget.AbsListView$FlingRunnable.run(AbsListView.java:4087)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:531)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5227)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:112)
at dalvik.system.NativeStart.main(Native Method)
第 79 行是这个:
vh.number.setText(s.getReadState());