Android local variable get's lost when using camera intent
I'm dealing with a random problem which related to camera usage. Before I call camera intent - I generate UUID to store file with this name. I store this UUID in private variable like so:
private St开发者_如何学运维ring requestedFileName;
When camera done - I'm processing this file, looks something like this:
public void onPictureTaken(int index)
{
//First of all - remember picture in database for reference.
FileData.InsertFile(mContext, UUID.fromString(requestedFileName));
//Reduce taken picture if needed, otherwise let it be original.
if (Preferences.getImageSize(mContext) > 0)
{
Imaging.scaleImageFile(mContext, requestedFileName, Preferences.getImageSize(mContext));
}
I see users report issue exception that boils down to requestedFileName == null when onPictureTaken called
Caused by: java.lang.NullPointerException
at java.util.UUID.fromString(UUID.java:210)
at com.idatt.views.FourImagesView.onPictureTaken(FourImagesView.java:151)
at com.idatt.views.TrailerUnitView.onPictureTaken(TrailerUnitView.java:233)
Everything works good on my phone (Nexus S) and in emulator. But users report this exception and I'm not sure why this is happening..
I've seen this happen on the Nexus phones, and some others. If you use DDMS to watch what is going on, I bet you'll see that your process is actually being terminated and then restarted. Thus your local state is being lost. You need to persist it, since Android can basically kill your process and restart it whenever it wants if you switch to a new task (and most of the camera capture intents set the NEWTASK flag).
If your class is an Activity
you can use onSaveInstanceState() to store your filename, then read it back out of the Bundle
you get in onCreate().
If you are not an Activity
you can use the SharedPreferences
store as a temporary place to save the filename:
private static void saveTempFileName(Context context, String filename) {
SharedPreferences settings = context.getSharedPreferences("whatever", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("com.yourstuff.whatever", filename);
editor.commit();
}
As @jeffamaphone noted you are probably having issues with app configuration changes. Application configuration change happens when something happens that affects the runtime environment of your app. Most notably this are: orientation change or keyboard hide/show.
Try this: start your app, invoke the Camera app (via your app action), change orientation, return to your app (via appropriate action). Does this sequence produce the error? Then you have issues with configuration change - when orientation changes usually (depending on your app settings) Android system restarts (kills and creates new instance) your Activity, which probably creates all new Views (without UUID set).
See handling configuration changes.
精彩评论