Search code examples
androidimagecameraonresume

Show captured picture when activity opened again


I have an activity that calls the camera intent to capture a picture and assign it as a profile picture. The activity works fine except that when I click back and then open the activity again the picture is not displayed anymore.

How can I make it show everytime the user opens this activity? Here's my code for that activity

public class MyAccountActivity extends Activity {

private static final int CAMERA_REQUEST = 1888;
private TextView name;
private TextView userId;
private TextView address;
private TextView email;
private TextView phone;
private ImageButton profilePicture;
private Bitmap bm;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_account);
    setUpViews();
Log.v("test","this is test: "+LoginActivity.user.getName());
}

private void setUpViews() {
    //setting up views

    //calling user details from User [] instance 

}

public void ViewPicture(View v) {
    Intent intent = new Intent(
    android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, 
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI.getPath()); 
            startActivityForResult(intent, CAMERA_REQUEST);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
        super.onActivityResult(requestCode, resultCode, data);
                bm = (Bitmap) data.getExtras().get("data");
                profilePicture.setImageBitmap(bm);
                MediaStore.Images.Media.insertImage(getContentResolver(), bm, null, null);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();  
                bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
                byte[] b = baos.toByteArray();  
}

I have tried to call profilePicture.setImageBitmap(bm) onResume() but my app crashes. Any help is much appreciated.


Solution

  • Save the captured image with some uri path

    Uri uri = Uri.withAppendedPath(Uri.fromFile(context.getExternalFilesDir(null)), imageName.png);
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, uri));
    

    then whenever you want to display the image, use this uri

    profilePicture.setImageUri(uri)