Ben Marten Ben Marten - 4 months ago 16
Java Question

How to get Notified when Method is Called on Object that does not Implement Observable?

I need to somehow know when the adapter of a ListView instance changes.

I was thinking of adding an observer to the listView object, but it does not implement the Observable interface.

ListView listView;
listView.addObserver(...); // method does not exist!


Is there any other way I can know when the adapter of a list view changes? e.g. the setAdapter() method is called... ?

--- UPDATE ---

Here's an code example:

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);


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

Answer

Turns out the Adapter gets notified when it's deregistered from the ListView, so I am using this:

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
  super.unregisterDataSetObserver(observer);

  Log.d("Adapter just got unregistered from the listView!");
  [...]
}