Bipin Gawand Bipin Gawand - 1 month ago 6
Android Question

Null pointer in customelist ListView in fragment

getting NullPointerException while setting custom adapter to listview.
my ListView is in Fragment.
............................................................................................................................................

Class 1:

public class Fragment_chats extends Fragment {
ListView lv;
String[] namem={"Gauri","Jayesh","Nitya","Rupali","Lalit","Poonam"};
Integer[] imgm= {R.mipmap.a,R.mipmap.b,R.mipmap.c,R.mipmap.d,R.mipmap.e,R.mipmap.f};

public Fragment_chats() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

}


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreate(savedInstanceState);
View v= inflater.inflate(R.layout.fragment_fragment_chats, container, false);
lv=(ListView)getActivity().findViewById(R.id.lv);
customList cl=new customList(getActivity(),imgm,namem);
lv.setAdapter(cl);
return v;
}

}
Class 2:
class customList extends ArrayAdapter
{
Activity act;
String[] na;
Integer[] img;
public customList(Activity context, Integer[] resource, String[] objects) {
super(context, R.layout.chats, objects);
act=context;
na=objects;
img=resource;

}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
{
convertView = View.inflate (act,R.layout.chats, null);
}
ImageView iv= (ImageView) convertView.findViewById(R.id.imageView);
TextView name=(TextView)convertView.findViewById(R.id.textView1);
TextView chat=(TextView)convertView.findViewById(R.id.textView2);
iv.setImageResource(img[position]);
name.setText(na[position]);
chat.setText("chat");

return convertView;
}
}


Custom layout is R.layout.chats
fragment layout is R.layout.fragment_fragment_chats

Answer

You have an error in onCreateView method

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
super.onCreate(savedInstanceState);
   View v= inflater.inflate(R.layout.fragment_fragment_chats, container, false);
    lv=(ListView)getActivity().findViewById(R.id.lv); //<-this line has error
    customList cl=new customList(getActivity(),imgm,namem);
    lv.setAdapter(cl);
    return v;
}

replace this line

lv=(ListView)getActivity().findViewById(R.id.lv);

with this

lv=(ListView)v.findViewById(R.id.lv);