Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullPointerException in LayoutInflater inside the BaseAdapter getView() method

Here s my getView() method. I am getting null pointer exception while inflating. There are so many answers for the same questions. This is used inside a fragment. But that doesn't suit me.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Context con = null;
    View vi=convertView;
    if(convertView==null){
            LayoutInflater inflater = (LayoutInflater)con.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            vi = inflater.inflate(R.layout.stores_listview_layout, null);
     }

     TextView tv = (TextView)vi.findViewById(R.id.store_name);
     tv.setText(storeData.get(position).get("merchantName"));

    return vi;
}

What is the mistake I am doing here?

Update: This works!

         View vi=convertView;
         Context c = null;
         if(convertView==null){
         LayoutInflater inflater = getLayoutInflater(null);
         vi = inflater.inflate(R.layout.stores_listview_layout, parent, false);
        }
like image 981
intrepidkarthi Avatar asked Dec 19 '25 00:12

intrepidkarthi


2 Answers

LayoutInflater inflater = getLayoutInflater(null);
vi = inflater.inflate(R.layout.stores_listview_layout, parent, false);
like image 158
mukesh Avatar answered Dec 20 '25 12:12

mukesh


Instead of declaring Context con; and then using it - which as pointed out is causing the null pointer exception you can simply use convertView.getContext()

Check the docs here


Have just actually thought about it and my first thought wouldn't work - Doh!

Since your code is inside a fragment you can access the layoutinflater via getActivity()

public View getView (int position, View convertView, ViewGroup parent){
    if( convertView == null ){
        //you can access layout inflater by accessing hosting activity
        convertView = getActivity().getLayoutInflater().inflate(R.layout.stores_listview_layout, parent, false);
    }
    TextView tv = (TextView)convertView.findViewById(R.id.store_name);
    tv.setText(storeData.get(position).get("merchantName"));
    return convertView;
}
like image 32
Paul D'Ambra Avatar answered Dec 20 '25 14:12

Paul D'Ambra