rafvasq
rafvasq

Reputation: 1522

How do I save an ArrayList<Uri> on screen rotate?

I have an ArrayList of URIs that I use in order to be able to iterate through the images and updating a single ImageView each time. I get a NullPointerException when I get close to doing this and I believe it has to do with the camera rotating my screen (destroying the activity) when it comes up to take the previously mentioned pictures.

What might this look like with onSaveInstanceState and onResume--?

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageURI(android.net.Uri)' on a null object reference
at plaidshorts.rafael.myapplication.Person1Screen$5.onClick(Person1Screen.java:124)
at android.view.View.performClick(View.java:5209)
at android.view.View$PerformClick.run(View.java:21174)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5477)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Line 124 is:

mainView.setImageURI(happyList.get(0));

My dispatchTakePictureIntent prompts for Camera or Gallery twice (see the loop at the beginning). OnActivityResult then takes the URI and adds it to happyList (which was instantiated in onCreate).

private void dispatchTakePictureIntent() {
    pictureCounter = -1;
    for(int i = 0; i < 2; i++) {
        pictureCounter++;
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
                outputFileUri = Uri.fromFile(photoFile);
            } catch (IOException ex) {
                Log.w("error","IOException");
            }catch (NullPointerException nullEx) {
                Log.w("error","NullPointerException");
            }
            // Camera.
            final List<Intent> cameraIntents = new ArrayList<Intent>();
            final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            final PackageManager packageManager = getPackageManager();
            final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
            for (ResolveInfo res : listCam) {
                final String packageName = res.activityInfo.packageName;
                final Intent intent = new Intent(captureIntent);
                intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
                intent.setPackage(packageName);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                cameraIntents.add(intent);
            }
            // Filesystem.
            final Intent galleryIntent = new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            // Chooser of filesystem options.
            final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
            // Add the camera options.
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[cameraIntents.size()]));
            startActivityForResult(chooserIntent, REQUEST_TAKE_PHOTO);
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_TAKE_PHOTO) {
                final boolean isCamera;
                if (data == null) {
                    isCamera = true;
                } else {
                    final String action = data.getAction();
                    if (action == null) {
                        isCamera = false;
                    } else {
                        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }
                Uri selectedImageUri;
                if (isCamera) {
                    selectedImageUri = outputFileUri;
                } else {
                    selectedImageUri = data == null ? null : data.getData();
                }
               // mainView.setImageURI(selectedImageUri);
               // Log.d("Before adding", selectedImageUri.toString());
                happyList.add(selectedImageUri);
            }
        }
    }

Upvotes: 1

Views: 779

Answers (3)

Jitesh Prajapati
Jitesh Prajapati

Reputation: 2533

store your data in onSaveInstanceState()

@Override
public void onSaveInstanceState (Bundle outState) {
    // TODO Auto-generated method stub
    super.onSaveInstanceState(outState);
    outState.putSerializable("array", arrayDetails);
}

put these lines of code in OnCreate() method of your activity to get arrayList on Orientation Change.

if (savedInstanceState != null) {
      arrayDetails = (ArrayList<yourListType>)savedInstanceState.getSerializable("array");
}

Upvotes: 1

Chirag Jain
Chirag Jain

Reputation: 133

Hey you can simply override onRetainNonConfigurationInstance in your activity and return your arraylist object and in your onCreate() method check if your object is null or not if its null use getLastNonConfigurationInstance() to retrieve the object

//PseudoCode 
onRetainNonConfigurationInstance()  {

return arraylistObject;

}

oncreate(Bundle onSavedInstance){

if(arraylistObject == null){

arraylistObject = (cast properly)getLastNonConfigurationInstance();

}

} 

this is simplest one but use fragment to save state across rotation is recommended

Upvotes: 1

Elltz
Elltz

Reputation: 10859

ArrayList<URI> uris = ..
//inStop of your application
SharedPreference sp = context.getSharePreference("imagineThis",0);
SharedPreference.Editor ed = sp.edit();
byte i =0;
for(Uri u : uris){ i++;
   ed.put(String.valueOf(i), u.toString());}
ed.commit();
//in onrestart of your app
uris.clear();//provided is not null;
SharedPreference sp = context.getSharePreference("imagineThis",0);
SharedPreference.Editor ed = sp.edit();
for(String s : ((Map<String,String>)sp.getAll()).values()){
   uris.add(Uri.parse(s));
}
ed.clear();
ed.commit();

i think you are good now

Upvotes: 1

Related Questions