Sunday, November 24, 2013

Three Things That Tripped Me Up This Week

I've had a pretty productive week at work but here are three things that tripped me up this week. I'm putting them down in blog post format so that I'll remember them and maybe they'll help you as well.

1) Concurrent Modification Exception

So I was working on some code where I needed to loop through a collection of users and remove one when it meets a certain criteria. Which I coded up as:

        List users = um.getUsers();
        
        for (User user : users) {
            if (user.isAnAss()) {
                users.remove(user);
            }            
        }

Do you see the problem? No, neither did I as I wasn't thinking and luckily enough for most of my test runs the user who isAnAss was at the end of the List so the exception wasn't throw. When the isAnAss user was in the middle of the list BOOM! ConcurrentModificationException.

To get around this problem I ended up doing an old school iteration through the list.

        List users = um.getUsers();
        
        User user = null;
        for (int i = 0; i < users.size(); i++) {
            user = users.get(i);
            if (user.isAnAss()) {
                users.remove(user);
            }            
        }

2) Relative Layouts in Android are Slow for Complex Layout

I've been working on a lot of complex layouts for an Android app I'm working on and I was using the RelativeLayout judiciously. One of my dialogs was taking quite awhile to load and doing some profiling I determined it to be the measure method for the RelativeLayout was being called many, many times. Switching to a LinearLayout helped reduce these calls.

Romain Guy recently posted a slide deck on how RelativeLayout's are getting better in Android 4.4 and here is a video or Romain and Adam Powell talking about writing custom Android views.




3) Android's Handling of Images Sucks

It just sucks so hard. I was doing some performance tuning of one of our dialogs and found that about 90% of the time it was taking before being show was loading the three images it was using. Cache those images folks, doesn't matter how small they are.

2 comments:

Matthieu Hostache said...

You can resolve "Concurrent Modification Exception" with iterator too and use ".remove" on the iterator when user is a ass :)

Simon MacDonald said...

@Matthieu Hostache

You are totally right. I've been meaning to go back and update this blog post with the Iterator solution. The current bit of code has a bug in it as the size of the collection will change and that effectively skip a user in the list.