android - NullpointerException 覆盖 arrayadapter 中的 getview

标签 android

我正在尝试像这样覆盖 getview 方法:

public class MyArrayAdapter extends ArrayAdapter {
private final Context context;
  private final ArrayList<DataList> values;
  private final  LayoutInflater li = LayoutInflater.from(this.getContext());


  public MyArrayAdapter(Context context, int    textViewResourceId,ArrayList<DataList> values) {
    super(context,textViewResourceId, values);
    this.context = context;
    this.values = values;
  }

  @Override
    public View getView(int position, View convertView, ViewGroup parent) {
      ViewHolder holder;

        if(convertView==null){
            convertView=li.inflate(R.layout.simplerow,parent,false);
            holder=new ViewHolder();
            holder.text=(TextView)   convertView.findViewById(R.layout.simplerow);
            convertView.setTag(holder);
        }else{
            Log.d("a","entre else");
            holder=(ViewHolder)convertView.getTag();
       }
        DataList b=values.get(1);
        String c=b.toString();
        holder.text.setText(values.get(position).toString());
        try {

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return convertView;
    }

  static class ViewHolder {
      TextView text;
    }

每次我到达 holder.text.setText(values.get(position).toString()) 时,我都会收到 空指针异常 错误。 VALUES 是 DataList 类型的 arraylist,而 Datalist 是我的类,它返回两个字符串。我知道值不为空。

最佳答案

holder.text 抛出 NullPointerException 的原因是因为您使用了错误的 id:

convertView.findViewById(R.layout.simplerow);

因此 findViewById() 返回 null。尝试类似的东西:

convertView.findViewById(R.id.textView); // I made up a name, but notice the difference?

关于android - NullpointerException 覆盖 arrayadapter 中的 getview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15252965/

相关文章:

android - 在 Flutter 中按下后退按钮时关闭抽屉导航

android - 我如何查看 Activity 的每个部分占用了多少内存 - ImageView 、声音、动画?[android]

android - 如何通过 Android 安全地建立以下 HTTPS 连接

android:headerDividersEnabled 不工作

android - 在 Imageview 上同时合并两个 ColorMatrix 或应用两个或多个 ColorMatrix

java - oncreate 方法内部无法读取 php 文件的内容?

java - Android JNI 上的 "UnsatisfiedLinkError"

Android SQLite多WHERE

android - fitsSystemWindows 被 ConstraintLayout 忽略

android - 带有Android Media Player的DSP(数字声音处理)