I want to update the UI from a timer. That’s not a problem at all but when it comes to Gallery/ListViews it gets difficult. I have a Gallery with custom BaseAdapter. I need a counter for every (gallery) item (every item counts different depending on the items data). That counter should run outside of the main thread. In addition I don’t want to run 10 threads for 10 items of the gallery when just one item is visible. It’s not a problem to define a Handler and start a thread (the counting) in the adapters getView()-method when a item/view gets visible. I can think of something like the following code:
public class MyAdapter extends BaseAdapter {
static class ViewHolder {
//...
public Handler myHandler;
}
public View getView(int position, View convertView, ViewGroup parent) {
//...
// getView() gets called indefinite so first remove callback because it may be added already
holder.myHandler.removeCallbacks(myRunnable);
holder.myHandler.postDelayed(myRunnable, 0);
//...
}
}
The problem is to remove the callback for a view thats not visible anymore because in getView() I get noticed when a view becomes visible but I have no clue how to get the view (and thereby the holder and it’s handler) that became invisible to remove the callback.
Is there a(nother) approach to solve that?
Found a clean solution (if someone needs something like that). I needed to update a TextView to set the new counter value (every second).
In BaseAdapters getView I add the TextViews(s) to a WeakHashMap. The TextView is the key of the map. A key/value mapping will be removed if the key is no longer referenced. So I do not cause memory leaks. The GarbageCollector does the work.
A thread counts “counter objects” down and refreshes the TextViews with the corresponding values (GarbageCollector runs all the time so in my case the map consists mostly of 3 items because the gallery shows just one item. Due to GarbageCollection the map gets immediately cleared by “unused” TextViews specially when scrolling fast through the list/gallery)
BaseAdapter’s getView():
The counter:
Start/stop the counter: