Android 第二次从相机拍摄时无法加载图像
我一直在用相机拍摄图像。这是第一次,它工作得非常完美,我能够捕获图像并在ImageView中显示。但当我第二次尝试拍摄不同的图像时,它仍然显示相同的旧图像 这是我的照相机意图和onActivityResult()代码 活动AAndroid 第二次从相机拍摄时无法加载图像,android,image,imageview,android-camera,image-capture,Android,Image,Imageview,Android Camera,Image Capture,我一直在用相机拍摄图像。这是第一次,它工作得非常完美,我能够捕获图像并在ImageView中显示。但当我第二次尝试拍摄不同的图像时,它仍然显示相同的旧图像 这是我的照相机意图和onActivityResult()代码 活动A listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked @Override publ
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);
}
});
问题可能是ImageView没有刷新内容。 更改内容后,应尝试调用invalidate方法
imageView.setImageURI(imageUri);
imageView.invalidate();
如果我们查看
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)
,如果将uri
传递到已设置的方法equals()
,则ImageView
不会刷新自身。您的代码每次都保存到同一个文件中,因此Uri
s总是相同的
只需调用imageView.setImageURI(null)调用imageView.setImageURI(imageUri)之前的code>代码>。或者,您可以每次保存到不同的文件;例如,通过向文件名添加时间戳
>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();
}
private static final int-CAMERA_REQUEST=1;
私有静态最终int画廊_图像=2;
私有静态最终字符串标记=”;
按钮捕捉图像;
图像视图图像视图;
图像数据库;
位图b,图像;
MainActivity CameraActivity=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CameraActivity=此;
imageView=(imageView)findViewById(R.id.image\u视图);
数据库=新的ImageDatabase(此);
//将OnClick侦听器设置为按钮视图
captureImage=(按钮)findViewById(R.id.capture\u image);
captureImage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
i存储许可已授予();
}
});
//长按图像
imageView.setOnLongClickListener(新视图.OnLongClickListener(){
@凌驾
仅长按公共布尔值(视图v){
i存储许可已授予();
返回true;
}
});
}
私有void startDialog(){
AlertDialog.Builder myAlertDialog=新建AlertDialog.Builder(
摄像活动);
myAlertDialog.setTitle(“上传图片选项”);
myAlertDialog.setMessage(“您想如何设置图片?”);
myAlertDialog.setPositiveButton(“Gallery”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口arg0,int arg1){
意图i=新意图();
i、 setType(“image/*”);
i、 setAction(Intent.ACTION\u GET\u CONTENT);
startActivityForResult(i.createChooser(i,“结果加载图像”)
,画廊(图片);
}
});
myAlertDialog.setNegativeButton(“摄像头”,
新建DialogInterface.OnClickListener(){
公共void onClick(对话框接口arg0,int arg1){
Intent cameraIntent=新的Intent(MediaStore.ACTION\u IMAGE\u CAPTURE);
startActivityForResult(摄像机帐篷、摄像机请求);
}
});
myAlertDialog.show();
}
@凌驾
ActivityResult上的公共void(int请求代码、int结果代码、意图数据){
if(requestCode==CAMERA\u请求和&resultCode==Activity.RESULT\u确定){
theImage=(位图)data.getExtras().get(“数据”);
}
if(requestCode==GALLERY\u IMAGE&&resultCode==RESULT\u OK){
试一试{
Uri imageUri=data.getData();
InputStream imageStream=getContentResolver().openInputStream(imageUri);
theImage=BitmapFactory.decodeStream(图像流);
}catch(filenotfounde异常){
e、 printStackTrace();
}
}
ByteArrayOutputStream=新建ByteArrayOutputStream();
压缩图像(Bitmap.CompressFormat.PNG,100,流);
byte[]byteArray=stream.toByteArray();
SQLiteDatabase db=database.getWritableDatabase();
ContentValues=新的ContentValues();
value.put(ImageDatabase.KEY\u IMG\u URL,byteArray);
db.insert(ImageDatabase.TABLE_NAME,null,value);
更新(ImageDatabase.TABLE_名称、值、null、null);
db.close();
}
public void getTheImage(){
SQLiteDatabase db=database.getReadableDatabase();
Cursor Cursor=(Cursor)db.rawQuery(“选择*自”+ImageDatabase.TABLE_名称,
空,空);
if(cursor.moveToFirst()){
字节[]imgByte=cursor.getBlob(cursor.getColumnIndex(ImageDatabase.KEY\u IMG\u URL));
cursor.close();
b=位图工厂.decodeByteArray(imgByte,0,imgByte.length);
}
if(cursor!=null&!cursor.isClosed()){
cursor.close();
}
设置图像位图(b);
}
//存储权限
公共布尔值IsStorage PermissionGrated(){
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.M){
if(checkSelfPermission(android.Manifest.permission.WRITE\u外部存储)
==PackageManager.权限(已授予){
Log.v(标记“已授予许可”);
startDialog();
返回true;
}否则{
Log.v(标记“权限被撤销”);
ActivityCompat.requestPermissions(此,新字符串[])
{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
返回false;
}
}else{//在sdk上自动授予权限
>To display image which is captured by camera on second time, Simply **update** the first element from database after completing the operation .
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();
}