简体   繁体   中英

Android null object reference exception

I am creating an application which reads data from local json file and display it as a Listview .I have also created a custom adapter for that.The problem is when i set the list's view using getView method it says following error

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

here is my code

 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;
    } 

Help me to solve this problem.

Change

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

to

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

your holder.id and holder.name are null at

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM