I am trying to update my Activity’s ListView from within the onLocationChanged function of a Location Listener using notifyDatasetChanged() but it doesnt work. I can however use setListAdapter from the same point in my code and this will work.
Here is my code:
public class TestListeners extends ListActivity {
ArrayAdapter adapter;
private final LocationListener networkLocationListener = new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
switch (status) {
case LocationProvider.AVAILABLE:
break;
case LocationProvider.OUT_OF_SERVICE:
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
break;
}
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
@Override
public void onLocationChanged(Location location) {
checkProximity(location.getLatitude(), location.getLongitude(), cx);
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get a list here venueNamesArray
//etc
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
venueNamesArray);
setListAdapter(adapter);
}
private void checkProximity(double curLat, double curLon, Context cx) {
//get a different list here venueNamesArray
//etc
adapter = new ArrayAdapter<String>(getApplicationContext(),
android.R.layout.simple_list_item_1, android.R.id.text1,
venueNamesArray);
adapter.notifyDataSetChanged();//this doesnt work and no error is thrown
setListAdapter(adapter);//this works
}
}
The reason I want to use notifyDatasetChanged() instead of setListAdapter is because the listview scrolls back to the top upon setting it. No error is throw when I use notifyDatasetChanged() so it is hard for me to see why this isnt working.
I have tried using a normal ListView for this instead of extending ListActivity and ran into the same problem.
because you are creating a new adapter every time. you are not only changing the data in same adapter that is currently linked to list ……..
As you are creating the new adapter and new adter will not linked with list untill you call setAdpter So it is not worth to call adapter.notifyDataSetChanged(); for adtper that is not linked with the list…
Solution
There is no need to create the adapter each time . jsut create and set in once in On-create and only change the ArrayList (add/remove not create new) and call adapter.notifyDataSetChanged();