我有一个Uri对象的问题。用户应该拍一张照片,然后将其发送到Firebase Storage。但是onActivityResult是错误的。
我读了很多主题(https://developer.android.com/training/camera/photobasics.html, StackOverFlow也是),但这段代码不起作用。
有一个错误:
尝试在空对象引用上调用虚拟方法'java.lang.String android.net.Uri.getLastPathSegment()'
下面是代码:
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
}
正如我所检查的,数据(意图)在onActivityResult等于NULL,所以uri也是空的。
那么,我如何解决这个挑战并使其可用呢?我应该使用位图来访问照片吗?
有人能帮我解决这个问题吗?对
我用我的问题弄明白了。
private ProgressDialog mProgress;
private Button mUploadBtn;
private ImageView mImageView;
Uri picUri;
private StorageReference mStorage;
private static final int CAMERA_REQUEST_CODE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mStorage = FirebaseStorage.getInstance().getReference();
mUploadBtn = (Button) findViewById(R.id.uploadBtn);
mImageView = (ImageView) findViewById(R.id.imageView);
mProgress = new ProgressDialog(this);
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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, CAMERA_REQUEST_CODE);
}
});
}
/** 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
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK ) {
mProgress.setMessage("Uploading Image...");
mProgress.show();
Uri uri = picUri;
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
mProgress.dismiss();
Uri downloadUri = taskSnapshot.getDownloadUrl();
Picasso.with(MainActivity.this).load(downloadUri).fit().centerCrop().into(mImageView);
Toast.makeText(MainActivity.this, "Upload Done.", Toast.LENGTH_LONG).show();
}
});
}
}
始终使用以下路径创建文件并存储捕获的图像
File photoFile = null;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (intent.resolveActivity(getPackageManager()) != null) {
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File
ex.printStackTrace();
}
// Continue only if the File was successfully created
if (photoFile != null) {
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
});
}
private File createImageFile() throws IOException {
// Create an image mSelectedFile name
String timeStamp = new SimpleDateFormat(Constants.PHOTO_DATE_FORMAT, Locale.ENGLISH).format(new Date());
String imageFileName = "IMG_" + timeStamp;
File storageDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES);
File file = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
return file;
}
然后使用这个文件"photoFile",并根据需要在onActivityResult中使用它。
我以前遇到过同样的问题,所以我确保我检查了我可以检查的一切,当onActivityResult
被调用时,下面是我的代码。
首先,我使用这个意图来捕获图像
File photoFile;
URI uri;
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePhotoIntent.resolveActivity(getPackageManager()) != null)
{
try
{
photoFile = Create_ImageFile();
}
catch (Exception e)
{
Log.e("file", e.toString());
}
if (photoFile != null)
{
takePhotoIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile.getAbsoluteFile()));
}
}
startActivityForResult(takePhotoIntent, CAMERA_REQUEST_CODE);
}
});
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent)
{
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case CAMERA_REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
try
{
Uri selectedImageURI = null;
ByteArrayOutputStream bos;
Bitmap bitmap = null;
int orientation;
ExifInterface exif = null;
FileOutputStream fos = null;
bos = new ByteArrayOutputStream();
try
{
uri=imageReturnedIntent.getData();
selectedImageURI = imageReturnedIntent.getData();
bitmap= BitmapFactory.decodeFile(GetRealPathFromURI(selectedImageURI));
exif = new ExifInterface(GetRealPathFromURI(selectedImageURI));
fos = new FileOutputStream(GetRealPathFromURI(selectedImageURI));
}
catch (Exception e)
{
e.printStackTrace();
}
if(bitmap==null)
{
uri=Uri.fromFile(photoFile.getAbsoluteFile()));
bitmap=BitmapFactory.decodeFile(photoFile.getAbsolutePath());
exif = new ExifInterface(photoFile.getAbsolutePath());
fos = new FileOutputStream(photoFile.getAbsolutePath());
}
if(bitmap==null)
{
String imagePath = getPathGalleryImage(imageReturnedIntent);
bitmap = BitmapFactory.decodeFile(imagePath);
exif = new ExifInterface(imagePath);
fos = new FileOutputStream(imagePath);
}
Log.e("PhotoFile",photoFile.getAbsolutePath());
// Bitmap bitmap =(Bitmap) imageReturnedIntent.getExtras().get("data");
//bitmap = Bitmap.createScaledBitmap(bitmap,bitmap.getWidth(),bitmap.getHeight(), false);
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);
Log.e("ExifInteface .........", "rotation ="+orientation);
//exif.setAttribute(ExifInterface.ORIENTATION_ROTATE_90, 90);
Log.e("orientation", "" + orientation);
Matrix m = new Matrix();
if ((orientation == ExifInterface.ORIENTATION_ROTATE_180)) {
m.postRotate(180);
//m.postScale((float) bm.getWidth(), (float) bm.getHeight());
// if(m.preRotate(90)){
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
} else if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
m.postRotate(90);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else if (orientation == ExifInterface.ORIENTATION_ROTATE_270)
{
m.postRotate(270);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
else
{
m.postRotate(0);
Log.e("in orientation", "" + orientation);
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),bitmap.getHeight(), m, true);
}
//CropImage.activity(selectedImageURI).setGuidelines(CropImageView.Guidelines.ON).start(this);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, bos);
userProfileIMG.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("Photos").child(uri.getLastPathSegment());
}
catch (Exception e)
{
e.printStackTrace();
}
}
break;
}
}
private String getPathGalleryImage(Intent imageURI)
{
Uri selectedImage = imageURI.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
return imagePath;
}
/**
* When image is returned we get its real path
**/
private String GetRealPathFromURI(Uri contentURI)
{
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
// Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
private File Create_ImageFile() throws IOException
{
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "JPEG_" + timeStamp;
File mediaStorageDir = getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = new File(mediaStorageDir.getAbsolutePath() + File.separator + imageFileName);
return image;
}
在这个过程之后,我总是结束了一个位图,以使用它作为我想要的
使用
获取实际图像的预定义路径Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
this.startActivityForResult(cameraIntent, 101);
捕获图像后,您可以在cameraIntent中设置的路径上获取捕获图像。如果你不想设置预定义的路径,那么检查Intent data。
if (resultCode == android.app.Activity.RESULT_OK && requestCode == 101) {
try {
path_mm = "Onsuccess_resultcode";
generateNoteOnSD("photo34.txt", path_mm);
Bitmap photo = null;
if (data == null) {
//get Bitmap here.
}
else {
Uri u1 = data.getData();
//get uri and find actual path on that uri.
}
}catch(Exception ex)
{}}