3

I have been using Camera Intent to capture images. For the first time it works perfectly and I am able to capture image and show that in ImageView. But when I try second time to capture a different image it still shows the same old image.

Here is my code for Camera Intent and onActivityResult()

       Uri selectedImage;
        private Uri imageUri;


         private void activeTakePhoto() {

                            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
                            intent.putExtra(MediaStore.EXTRA_OUTPUT,
                                    Uri.fromFile(photo));
                            imageUri = Uri.fromFile(photo);
                            startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
                        }


      @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            switch (requestCode) {
                case RESULT_LOAD_IMAGE:
                    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK & null != data) {
                        selectedImage = data.getData();
                        imageView.setImageURI(selectedImage);
                    }

                    break;

                case REQUEST_IMAGE_CAPTURE:
                    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                        try {
                            selectedImage = imageUri;
                            getContentResolver().notifyChange(selectedImage, null);
                            imageView.setImageURI(imageUri);
                        } catch (Exception e) {
                            Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                                    .show();
                            Log.e("Camera", e.toString());
                        }
                        Log.e("A", "AAA");
                    }
            }
        }


   submit.setOnClickListener(new View.OnClickListener() { // back to Activity A listView
            @Override
            public void onClick(View v) {
                Intent returnIntent = new Intent();
                amount = Amount.getText().toString();
                description = Description.getText().toString();
                type = spinnerType.getSelectedItem().toString();
                returnIntent.putExtra("type", type);
                returnIntent.putExtra("description", description);
                returnIntent.putExtra("amount", amount);
                if(selectedImage!=null) {
                    returnIntent.putExtra("img_uri", selectedImage.toString());
                }
                setResult(Activity.RESULT_OK, returnIntent);
                finish();
            }
        });

Activity A

 listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) { // if list is clicked
                mClickedPosition = position;
                Object o = listview.getItemAtPosition(position);
                ImageAndText image = (ImageAndText) o;
                String type = image.getType();
                String amount = image.getAmount();
                String description = image.getDescription();
                Uri photo = image.getImage();
                String[] type1 = type.split(":");
                String[] amount1 = amount.split(":");
                String[] description1 = description.split(":");
                Intent i = new Intent(getApplication(), AddMoreClaims.class);
                i.putExtra("type", type1[1].toString().trim());
                i.putExtra("amount", amount1[1].toString().trim());
                i.putExtra("description", description1[1].toString().trim());
                i.putExtra("photo", photo);
                startActivityForResult(i, PROJECT_REQUEST_CODE);
            }
        });

Edited(add TimeStamp)

 private void activeTakePhoto() {
        String filename = "Pic_" + System.currentTimeMillis() + ".jpg";
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                Uri.fromFile(photo,filename));
        imageUri = Uri.fromFile(photo,filename);
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE);
    }
John Joe
  • 12,412
  • 16
  • 70
  • 135

3 Answers3

3

If we take a look at the source for ImageView, the setImageURI() method starts out with an if check similar to:

public void setImageURI(@Nullable Uri uri) {
    if (mResource != 0 ||
            (mUri != uri &&
             (uri == null || mUri == null || !uri.equals(mUri)))) {

        // Drawable resolution and update code
    }
}

As you can see from !uri.equals(mUri), the ImageView won't refresh itself if the Uri passed into the method equals() that already set. Your code is saving to the same file each time, so the Uris are always going to be the same.

Simply call imageView.setImageURI(null); before calling imageView.setImageURI(imageUri);. Alternatively, you could save to a different file each time; for example, by adding a timestamp to the filename.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
0

The Problem could be that the ImageView doesn't refresh the content. You should try calling the invalidate method, after changing the content.

imageView.setImageURI(imageUri);
imageView.invalidate();
Philipp Hellmayr
  • 312
  • 2
  • 11
0
>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .   

public class MainActivity extends AppCompatActivity {

private static final int CAMERA_REQUEST = 1;
private static final int GALLERY_IMAGE = 2;
private static final String TAG = "";
Button captureImage;
ImageView imageView;
ImageDatabase database;
Bitmap b,theImage;
MainActivity CameraActivity = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    CameraActivity = this;

    imageView = (ImageView) findViewById(R.id.image_view);
    database = new ImageDatabase(this);

    //Set OnClick Listener to button view
    captureImage = (Button) findViewById(R.id.capture_image);
    captureImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            isStoragePermissionGranted();
        }
    });

    //long press on image
    imageView.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            isStoragePermissionGranted();
            return true;
        }
    });
}

private void startDialog() {
    AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(
            CameraActivity);
    myAlertDialog.setTitle("Upload Pictures Option");
    myAlertDialog.setMessage("How do you want to set your picture?");

    myAlertDialog.setPositiveButton("Gallery",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {
                    Intent i = new Intent();
                    i.setType("image/*");
                    i.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(i.createChooser(i, "Result load Image")
                            , GALLERY_IMAGE);
                }
            });

    myAlertDialog.setNegativeButton("Camera",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface arg0, int arg1) {

                    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(cameraIntent, CAMERA_REQUEST);
                }
            });
    myAlertDialog.show();
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {

        theImage = (Bitmap) data.getExtras().get("data");

    }

    if (requestCode == GALLERY_IMAGE && resultCode == RESULT_OK) {
        try {
            Uri imageUri = data.getData();
            InputStream imageStream = getContentResolver().openInputStream(imageUri);
            theImage = BitmapFactory.decodeStream(imageStream);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        theImage.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] byteArray = stream.toByteArray();

        SQLiteDatabase db = database.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ImageDatabase.KEY_IMG_URL, byteArray);
        db.insert(ImageDatabase.TABLE_NAME, null, values);
        db.update(ImageDatabase.TABLE_NAME, values, null, null);
        db.close();

}

public void getTheImage() {

    SQLiteDatabase db = database.getReadableDatabase();

    Cursor cursor = (Cursor) db.rawQuery(" SELECT * FROM " + ImageDatabase.TABLE_NAME,
            null, null);
    if (cursor.moveToFirst()) {
        byte[] imgByte = cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY_IMG_URL));
        cursor.close();
        b = BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);

    }
    if (cursor != null && !cursor.isClosed()) {
        cursor.close();
    }
    imageView.setImageBitmap(b);

}

//Storage permission
public boolean isStoragePermissionGranted() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                == PackageManager.PERMISSION_GRANTED) {
            Log.v(TAG, "Permission is granted");
            startDialog();
            return true;
        } else {

            Log.v(TAG, "Permission is revoked");
            ActivityCompat.requestPermissions(this, new String[]
                    {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            return false;
        }
    } else { //permission is automatically granted on sdk<23 upon installation
        Log.v(TAG, "Permission is granted");
        startDialog();
        return true;
    }
}

@Override
protected void onStart() {
    super.onStart();
    getTheImage();
}

}

SHAZAM
  • 21
  • 4