One of the many new features added in Android 4.2 was support for multiple users on a single device. This is a pretty cool feature from a user’s perspective. And from a developer’s perspective, the great news is that “there’s nothing different you need to do in order for your app to work properly with multiple users on a single device.”
Well, not quite. If you keep reading that document, you will notice there are a couple of caveats. A very important one is to make sure that you are using the correct path to the user’s files. I have seen many examples around the web and elsewhere (including my own code) that uses hard-coded paths to access files in the private storage area. The code often looks something like this:
String filename = "/data/data/com.example.mycoolapp/databases/cool.db";
This code has worked great for a very long time, but if you want to support multiple users on a single device, this code will fail. Why? Well, the implementation of multiple user support separates the private files of each user from those of all other users on that device. This is a good thing as it means that users don’t have to worry about their files being exposed to those who shouldn’t see them. In order to do this, Android gives each user a unique space in the file system. So, while
/data/data/com.example.mycoolapp might work for the administrator user on the device, another user attempting to access
/data/data/com.example.mycoolapp will receive an error indicating that he or she does not have privileges to that location. That location is, in fact, owned by the administrative user and not the second user.
So, how to solve the problem? Google tells you right in the Android 4.2 APIs document, but ultimately the change is very simple. You just need to make sure that you have a Context reference available. To fix my example above, I would simply change that line as follows:
String filename = context.getFilesDir().getAbsolutePath() + "/databases/cool.db";
An easy, one-line code change that will save you the headaches and confusion that would have come when your users started reporting strange errors and the inability to use your app on their Android 4.2 tablets.