Archive for September, 2010

Google analytics drops metrics in Android if you send them too quickly

I just ran into this problem with the Google Analytics SDK for Android (v0.8). Basically, if you try to send too many pageviews too quickly, the tracker gets overwhelmed and forgets to track some of them.

My solution was just to space things out a bit with Timers and TimerTasks. I have a small wrapper around the analytics tracker, which has a timer, a static inner TimerTask class, and a long which is the soonest that a pageview should be sent. Whenever you want to send a pageview, you just call recordView, which looks like this:

public void recordView(String metric) {
        // The current time.
        long time = new Date().getTime();
        // We keep track of the next appropriate time to send a metric with sendTime. sendTime only gets updated
        // when we try to send something,
        if (this.sendTime > time) {
                time = this.sendTime;
        this.sendTimer.schedule(new TrackTask(this, metric), new Date(time));
        // I have sendInterval set to 2000, meaning pageviews are sent at a minimum, two seconds apart.
        this.sendTime = time + this.sendInterval;

Then, TrackTask looks like this:

protected static class TrackTask extends TimerTask {
        private WeakReference ref;
        private String metric;

        public TrackTask(Metrics met, String metric) {
                // WeakReference to avoid memory leaks.
                this.ref = new WeakReference(met);
                this.metric = metric;

        public void run() {
                // try catch block because our WeakReference has the possibility of being GCed out from under us.
                try {
                } catch (NullPointerException e) {

Comments off

Getting items in a ListView to show Alpha values

So I was trying to implement a ListView in Android the other day where the items would have varying levels of alpha transparency in the background. For some reason, every item’s background would go black whenever the ListView scrolled. (presumably for performance reasons.) Googling around yielded not much, but a co-worker had solved this problem in a previous app. Looking through the layout file, I saw that the android:cacheColorHint was set in his layout, but not mine. Adding it solved the problem.

Basically, just adding android:cacheColorHint=”#00000000″ to the ListView enabled transparency while scrolling.

Comments off

Related Links

Resource Links