android - Marshmallow 和 Nougat+ 中的相机意图活动有何不同?
问题描述
我有以下代码在 android 6 中工作,但在 android 7+ 中使用它时,应用程序崩溃并出现 nullpointerexception。
Intent intentfile = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intentfile, SELECT_PHOTO);
在活动结果中,代码是
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
selectedImage = data.getData();
Picasso.get().load(selectedImage).fit().centerCrop().into(imageView);
imgselect.setVisibility(Button.INVISIBLE);
relativeLayout.setVisibility(RelativeLayout.VISIBLE);
upload.setVisibility(Button.VISIBLE);
下一个代码是将选定的图像上传到服务器
String sourcepath = getRealPathFromURI(this, selectedImage);
final String filename = sourcepath.substring(sourcepath.lastIndexOf("/") + 1);
final String destinationpath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/DiaryApp/Images/";
copyFile(sourcepath, filename, destinationpath);
imageRef = storageRef.child(firebaseUser.getUid() + "/Images/" + filename);
//creating and showing progress dialog
progressDialog = new ProgressDialog(this);
progressDialog.setMax(100);
progressDialog.setMessage("Uploading...");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
progressDialog.setCancelable(false);
//starting upload
uploadTask = imageRef.putFile(selectedImage);
// Observe state change events such as progress, pause, and resume
uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
@Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
//sets and increments value of progressbar
progressDialog.incrementProgressBy((int) progress);
}
});
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(view.getContext(), "Error in uploading!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Toast.makeText(view.getContext(), "Upload successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
//showing the uploaded image in ImageView using the download url
Image image = new Image(editText.getText().toString(), "Image", "file:" + destinationpath + filename, downloadUrl + "", getDate(), getTime());
userDataRef.child("data").child(userDataRef.push().getKey()).setValue(image);
finish();
现在方法 getRealPathFromUri(this,selectedImage);
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
if(contentUri.toString().contains("images")) //Error is here in this line {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else if(contentUri.toString().contains("video")){
String[] proj = {MediaStore.Video.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else {
return "Empty";
}
}
finally {
if (cursor != null) {
cursor.close();
}
}
}
selectedimage 在 android 7+ 中为空,而在较小的 android 版本中它正在工作?
解决方案
试试下面的代码 -
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File file=getOutputMediaFile(1);
picUri = Uri.fromFile(file); // create
i.putExtra(MediaStore.EXTRA_OUTPUT,picUri); // set the image file
startActivityForResult(i, CAPTURE_IMAGE);
会在哪里getOutputMediaFile(int)
——
/** Create a File for saving an image */
private File getOutputMediaFile(int type){
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "MyApplication");
/**Create the storage directory if it does not exist*/
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
/**Create a media file name*/
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == 1){
mediaFile = new File(mediaStorageDir.getPath() + File.separator +
"IMG_"+ timeStamp + ".png");
} else {
return null;
}
return mediaFile;
}
最后——
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Intent i;
switch (requestCode) {
case CAPTURE_IMAGE:
//THIS IS YOUR Uri
Uri uri=picUri;
break;
}
}
}
推荐阅读
- scala - 如何使用while循环将数据收集到单个列表中?
- django - ImageField url 属性
- python - Python Pandas DataFrame 中具有 IF 条件的 Lambda 函数行为异常
- c - 如何通过 liburing 实现每秒零纳秒的计时器?
- flutter - Flutter:TextFormField:调用setState()后光标重置为开始
- security - 如何保护我的应用程序中写入的数据,如密码
- java - H2 java.lang.ClassNotFoundException 用于在类路径中传递的触发器
- python - Python3 search by value in nested dictionaries and lists then get other nearest keys/values pair
- swift - How to put a sentence in a every line of List in Swift?
- python-3.x - Type Error: unsupported operand type(s) for /: 'Nonetype' and 'int'