Timers in Android

One thing that’s always been curious to me is the lack of a simple timer class in Android. Instead you need to work around the lack in one of two ways. The easiest way is via a Handler. Its not hard to do, but its a little bit of busy work. The problem with this is that it’s only appropriate for very short timers or for things tied heavily to the UI. Its a non-exact timer and may be delayed indefinitely if the activity is paused or the phone goes idle. It won’t last beyond the Context that sets it at all. The other way is via an alarm. Alarms are persistent across Contexts and may be fairly exact. But they’re based on BroadcastReceivers, which can be tricky to work with- since the app may be started to process the alarm and call to the BroadcastReceiver, you have to code it carefully to get any data to persist until the broadcast occurs. In addition, Google keeps changing the AlarmManager API with respect to how exact timers are and correctly using it is a bit tricky.
Continue reading

Two level caching

This post builds off my post for disk caching. Sometimes you want a disk cache, to prevent unneeded network requests. Sometimes you want a memory cache, to put a cap on the amount of RAM you use. Sometimes you want both- you want a small fixed size working set in RAM, and a larger pool of objects saved to disk in case they’re needed. The solution is two level caching. The idea is that the memory cache is a subset of the disk cache, allowing you to page in from the disk cache to the memory cache as needed. Given you already have a disk cache (see previous post) the amount of extra code is pretty trivial. So I’ll skip the in depth discussion and just leave the solution here.
Continue reading

Disk caching on Android

Frequently when writing Android apps I’ll find the need for a cache. The classic case is with Bitmaps- adding all your bitmaps to a cache and grabbing them solely from the cache can solve a lot of OOM issues. And Google has written a great class, LRUCache, to easily enable memory caching. The problem is that memory caching frequently isn’t enough. If I have an app that needs to download lots of images from the net, I may need tens or hundreds of MB of images, and I don’t want to redownload them every time the app restarts or it falls out of a small memory cache. At the same time I don’t want to use up exponentially increasing amounts of disk space. The solution is to use a disk cache.
Continue reading

Why no posts lately

There haven’t been too many posts lately. Why? I’ve recently been relocated from the East Coast to Silicon Valley for work. I’m not free to discuss why that is, but I hope to be putting out some cool new tech soon. Unfortunately between that and my personal life, there hasn’t been time for blog posts. I’ll rectify that soon, but it could be another week or two first.

Reflection and JSON parsing

One of the things I most hate to do in programming is parsing JSON. Not because it’s hard, but because it’s trivial. That’s the problem- it’s boring yet very time consuming. I don’t want to have to write the line myvar = jsonValue.getInt(“myvarname”,0); 1000 times. I want to take a string and just suck it up into an object. Nowdays in Java I would just use GSON, a library by Google that uses reflection to do this and is used widely by the Java community. But there was a time before this library became popular and I actually had the same idea. Since I rarely used reflection (and still rarely use it, I find it’s generally a code smell) I thought it would be a great opportunity to learn. So here it is- my own personal JSON parsing library.

As an aside- I had originally planned on revisiting this code and expanding it for a part 2 on this, but I’ve decided there’s no value here over using GSON. So I’ll take some of the features I planned to add and use them elsewhere in the future, in a bit of a broader way. As a result this update is going to be lower in detail and more in code, since I have no interest in keeping this library updated and will be moving my libraries that depend on it to GSON. I’m posting this mainly to increase my ready to go post count and to provide an interesting example into using reflection.

Continue reading

Cropping to faces

Sometimes you read a question on the internet and wonder “Why isn’t that built in functionality? It can’t be too hard to do.” And occasionally when you see one of those you decide to jump onto it and write it yourself. That was the rabbit hole I fell down tonight. It all started with this question on Stack Overflow. Android has built in face detection on images. Why can’t you automatically crop to them? And for some reason it piqued my interest enough to write some code. Continue reading

Library Only Programmers

One thing that always surprises me when trying to help other programmers is the depths people are willing to go to in order to avoid actually writing code. When I started programming, your first reaction on being given a problem was either to jump into code/design or to jump into research on how you’d code/design a solution. These days, that doesn’t seem to be the case- the first thing most people seem to do is to look for a library to do it for them. And it seems to be getting worse- nowdays they aren’t just looking at the built in language libraries, they’ll jump straight to github and try to find something there.

This isn’t a good change. I’m not going to argue that all libraries are bad- that’s obviously silly. But there are times and places to use libraries, and times not to. Every library is a black box. It’s a piece of code from who knows where with unknown limitations, compromises, tradeoffs, and bugs. Open source libraries let you figure all that out, but let’s be honest- you’re not going to read them. I don’t read them unless I’m debugging a problem inside of them, somebody who’s idea of programming is to find libraries and slam them together definitely isn’t. And let’s not get into commercial libraries and the great gaping security whole they present. I recently had a commercial library I was integrating into an app that was randomly crashing. The library was supposed to handle certain gestures in a certain way. It was crashing because I didn’t have internet permission in the app. According to the authors, it was trying to upload a debug log. Maybe it was- but I have no way to know for sure. Maybe it was uploading their contacts, or their gps location, or some other piece of private info. The problem is I don’t know, and short of reverse engineering their library I can’t know.

The worst thing about this trend is that in general the people who should least be doing this are the ones most likely to do it. It tends to be the younger generation of programmers who are the worst offenders. These are the people who would learn the most by doing things themselves. Any time you write code, you learn. If you use a library you learn… how to use that library. If you write the functionality of the library, you learn how to really do what the library does, you learn why it does it that way, you learn about all the knobs and whistles on the library and why they’re there. Your goal as a programmer should always be to completely understand the task you’re doing and how to do it. You will never get that by looking for a library whenever something takes a few lines of code. And if you don’t know why and how you’re doing things, you’ll never be able to fix things when something goes wrong.

So when should you consider using a library? I’d argue there’s only three cases where you should:

1)When something is really hard and you aren’t qualified to do it. For example, I wanted to write an app that needed OCR (optical character recognition) technology. Computer vision is an extremely complex discipline, its not a solved problem. Writing a good OCR algorithm would take months- if I had all the knowledge needed to write one (I don’t). So I downloaded a well known library for it. Another great example is encryption- if you write your own you’re going to write something exploitable. It’s rarely a mistake to use a library for this reason, your biggest risk is picking the wrong one to use.

2)When its the only way to access a resource. If I wanted to interact with Facebook, I’d use Facebook’s library. I can be fairly certain its well debugged, and the only other way to access that information would be to reverse engineer the library and replicate what it does. That would be an obvious waste of time. This is the one time you should definitely use a library.

3)When you know how to do something, but doing it well would take a long time. A good example of this is parsing a well known but complex file format. Recently I had an app that needed to draw and annotate pdf files. Doing this on my own would have taken a few weeks to write and a few months to debug. Buying a library allowed me to implement it in a few days. The trick here is to make sure you know what you need and make sure the library supports it up front. Switching libraries here or having to make major modifications to it to add or change how it works will have a huge cost- possibly a higher cost than just doing it on your own from the beginning. A great example of that comes from the same app- I needed a color picking dialog. None is built into Android and it would have been boring to write, so I picked one online and popped it in. A week later we decided we needed one with transparency capability. The library didn’t have one. So now not only did I waste a day researching libraries and implementing one, I had to rewrite it on my own anyway. It took me a day to write. I would have been better off going on my own.

I know I’m going to get someone here with the feedback “But Gabe, if you write it yourself there will be bugs!”. Maybe. But using a library doesn’t eliminate bugs- libraries have bugs too. Sometimes those bugs are on you because you misused the library. Sometimes they’re on the library author. In either case, they tend to be very hard to find and fix. Generally when I write code myself I know where the weak points are, and I’ll know where to look as soon as you describe a problem. There’s no chance that will happen with a bug in a library. Besides, to be perfectly honest- I’m pretty damn good at this. Odds are I’m better than the guy who wrote the library. I’m less likely to have a bug than he is.

And one subrant: if your idea of looking for a library is ever to do a search on guthub- stop. Never do that again. So lets say you find one- you have a library of unknown license, unknown skill of author, unknown bugs, unknown code quality that may or may not be supported in the future. You’ve just lost 75% of the benefits of a library. If its a good library, searching in google for what you want will get you plenty of answers all linking to it. If there aren’t, you shouldn’t use it- a quality supported library will have a website somewhere. If you’re doing hobbyist work, you’ll learn more by replicating it than by downloading a library. And if you’re doing professional work, every one of those issues above are a disqualifier. Github is a place to store your source, its not a place to look for code.

A failed app

Two weeks ago I failed. I came up against a program I could not write. It took the laws of physics itself to break me, but it happened. I’m disappointed my app couldn’t be made to work, but I’m reminded that no time spent programming is wasted.

Continue reading

Location tracking

A few of you might know that I spend a lot of time helping on stackoverflow.com. One of the most ironic and frustrating things is when stackoverflow itself is the source of bad information. Sometimes bad code that mostly works gets voted up, and its impossible to fix it. So here’s my attempt to take one of those and do it right, in the hope I can help future newbies.

A common question asked is how to track your location via GPS. It’s a moderately complex API with a few corner cases that can trip up a beginner. So of course everyone wants to simplify it. Here’s the most common abstraction I see used- GPSTracker. Continue reading

Is the phone ringing?

About 2 years ago I was writing an app that needed to know when a call was happening.  More specifically, I needed to be able to detect when a call ended, its duration, and who it was made to.  The app was never released but it was a small app to categorize my calls so I could account for them and accurately charge for my consulting work (also so I could accurately deduct my business ratio of calls from my taxes).

This ended up being surprisingly annoying on Android.  Android’s method of sending events to activities that aren’t running (BroadcastReceivers) aren’t too bad, but they aren’t always convenient to work with.  Instead of getting specific functions called on an object somewhere, you get generic calls on an object with no context and no saved state.  In addition, Android doesn’t have call starting and call end broadcasts.  It has an outgoing call started broadcast, but call ends can only be detected by checking the ringing state changing and duration has to be calculated on your own.  Detection of outgoing calls needs to be detected in a similar way.

I’m ok with writing code like this once.  I pretty much have no choice.  But I’m not going to do it twice.  There’s better ways.

Continue reading