Search code examples
javaandroidlistviewgridviewlistadapter

How can a ListAdapter know when its Detached?


How can the firstAdapter know when it is detached from being the listView's actual adapter (because secondAdapter replaces it)?

final ListAdapter firstAdapter = new SimpleAdapter(
    this,
    new ArrayList<Map<String, Object>>(),
    android.R.layout.simple_list_item_1,
    new String[] {"AAA"},
    new int[] {android.R.id.text1}
);
final ListAdapter secondAdapter = new SimpleAdapter(
    this,
    new ArrayList<Map<String, Object>>(),
    android.R.layout.simple_list_item_1,
    new String[] {"AAA"},
    new int[] {android.R.id.text1}
);

setListAdapter(firstAdapter);

(new Timer()).schedule(new TimerTask() {
  @Override
  public void run() {
    Runnable r = new Runnable() {
      @Override
      public void run() {
        setListAdapter(secondAdapter);
      }
    };
    new Handler(Looper.getMainLooper()).post(r);
  }
}, 1000);

Solution

  • Turns out the first Adapter gets notified when it's deregistered from the ListView, so I am using: https://developer.android.com/reference/android/widget/Adapter.html#unregisterDataSetObserver(android.database.DataSetObserver)

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {
      super.unregisterDataSetObserver(observer);
    
      Log.d("Adapter just got unregistered from the listView!");
      [...]
    }