Android null对象引用异常

时间:2015-01-26 13:19:57

标签: android json gson

我正在创建一个从本地json文件中读取数据的应用程序,并将其显示为Listview。我还为此创建了一个自定义适配器。问题是当我设置列表时#39 ; s使用getView方法查看后面的错误

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference at com.example.nyqmind.jsondemo.MainActivity$MyCustomAdapter.getView

这是我的代码

 public View getView(int position, View convertView, ViewGroup parent){
        View row=convertView;
        ViewHolder holder;
        if(row==null) {
            LayoutInflater inflater = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.listview_layout, parent, false);
            holder=new ViewHolder();
            holder.id= (TextView) findViewById(R.id.textView2);
            holder.name= (TextView) findViewById(R.id.textView4);
            row.setTag(holder);
        }
        else
        {
            holder= (ViewHolder) convertView.getTag();
        }


        Employee list=emp.get(position);
        holder.id.setText(list.getid());
        holder.name.setText(list.getName());
        return row;
    } 

帮我解决这个问题。

1 个答案:

答案 0 :(得分:3)

更改

 holder.id= (TextView) findViewById(R.id.textView2);
 holder.name= (TextView) findViewById(R.id.textView4);

 holder.id= (TextView) row.findViewById(R.id.textView2);
 holder.name= (TextView) row.findViewById(R.id.textView4);

您的holder.idholder.name位于null

 holder.id.setText(list.getid());
 holder.name.setText(list.getName());