《棉花糖》和《牛轧糖+》中的镜头意图活动有何不同



我有下面的代码,它在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+中为null,而在较低版本的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;
}
}   
}

最新更新