Reputation: 55
I have been stuck on this problem for the last few hours so any help will be very much appreciated. Im getting this error Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
ArrayAdapter class
public class LocationsAdapter extends ArrayAdapter<String> {
public LocationsAdapter(Context context, ArrayList<String> locations) {
super(context, R.layout.location_list, locations);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
View customView = layoutInflater.inflate(R.layout.location_list, parent, false);
String name = getItem(position);
TextView textView = (TextView)customView.findViewById(R.id.locationTF);
textView.setText(name);
return customView;
}
}
activity_maps.xml
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listViewLocations" />
location_list.xml
<TextView
android:layout_width="135dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="@+id/locationTF"
android:layout_weight="0.03" />
MapsActivity class
private ArrayAdapter<String> adapter;
.
.
.
public void initAdapter(){
ArrayList<String> sl = new ArrayList<>();
sl.add("b");
adapter = new LocationsAdapter(this, sl);
ListView listView = (ListView) findViewById(R.id.listViewLocations);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
}
Upvotes: 0
Views: 898
Reputation: 192033
Please make sure you are using the correct layout file before you use findViewById with any id contained in that layout.
setContentView(R.layout.activity_maps);
Your problem is findViewById returned null because it couldn't find the id in the layout you've used
Upvotes: 1