第二次从相机拍摄时无法加载图像

时间:2016-01-13 16:58:04

标签: android image imageview android-camera image-capture

我一直在使用Camera Intent来捕捉图像。这是第一次完美运行,我能够捕获图像并在ImageView中显示。但是当我第二次尝试拍摄不同的图像时,它仍会显示相同的旧图像。

这是我的Camera Intent和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();
            }
        });

活动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);
            }
        });

已修改(添加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);
    }

3 个答案:

答案 0 :(得分:2)

如果我们查看ImageView的来源,则setImageURI()方法会以if检查开头,类似于:

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

        // Drawable resolution and update code
    }
}

正如您在!uri.equals(mUri)中看到的那样,ImageView如果Uri传入已设置的方法equals(),则不会自行刷新。您的代码每次都保存到同一个文件中,因此Uri始终是相同的。

在致电imageView.setImageURI(null);之前,只需致电imageView.setImageURI(imageUri);即可。或者,您可以每次保存到不同的文件;例如,通过向文件名添加时间戳。

答案 1 :(得分:0)

问题可能是ImageView没有刷新内容。 更改内容后,您应该尝试调用invalidate方法。

imageView.setImageURI(imageUri);
imageView.invalidate();

答案 2 :(得分:0)

>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .   

公共类MainActivity扩展了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();
}

}