1

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.

1 Answer 1

3

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());
Sign up to request clarification or add additional context in comments.

1 Comment

Also, if list.getId() returns a number, convert it to string before setting the text, otherwise you will get a ResourceNotFoundException

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.