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);
}
LayoutInflater inflater = getLayoutInflater(null);
vi = inflater.inflate(R.layout.stores_listview_layout, parent, false);
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With