0

I'm creating a listView that is constantly updated. And every time there is an update it comes back to the first item. I would like to maintain the poistion after every updating.

    public class Receiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {

    if(intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)){

         results = wifi.getScanResults();
         MonAdaptateurDeListe adaptateur = new MonAdaptateurDeListe();

             //list1.setAdapter(adaptateur); 

             if(list1.getAdapter()==null)
            {
                            list1.setAdapter(adaptateur);
            }
            else
                            {
            adaptateur.notifyDataSetChanged();
            //adaptateur.clear();
            list1.setAdapter(adaptateur);
            }
            }
                        }
}
apxcode
  • 7,696
  • 7
  • 30
  • 41
Amina
  • 723
  • 8
  • 20

2 Answers2

1

The root of the problem is because you call setAdapter() again. Try to hold a instance of the adapter as a field, during the creation, set it to the ListView and don't touch on the ListView anymore.

Now, when you receive updates, you just need to call a 'setter' method on your Adapter with your new data and call: notifyDataSetChanged()...don't call setAdapter() on every update.

Alécio Carvalho
  • 13,481
  • 5
  • 68
  • 74
0

as I said in the comments:

ListAdapter adapter = list.getAdapter();
if(adapter == null){
   adapter = new MonAdaptateurDeListe();
}else{
   // usually here you add the values to the adapter
   // for example, in case it's an ArrayAdapter you call `add(value)` on it
   adapter.notifyDataSetChanged()
}

that's because the list automatically remember position when you just change the data in the adapter. But if you're changing the whole adapter, it will reset.

Budius
  • 39,391
  • 16
  • 102
  • 144