我正在使用相机拍摄图像,并希望发送到firebase存储。但是我在3天内收到错误。我被困在上面了。当我触发intent时它捕获图像,但在onActivityresult中它返回请求代码= 1和结果代码= -1。这是我的代码
捐赠活动:
package com.example.manzoorhussain.kindnessapp;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DonationActivity extends AppCompatActivity {
private Button mUploadBtn;
private ImageView mImageView;
private final static int CAMERA_REQUEST_CODE = 1;
private StorageReference mstorage;
ProgressDialog progressDialog;
Uri photoURI;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_donation);
mUploadBtn = (Button) findViewById(R.id.upload);
mImageView = (ImageView) findViewById(R.id.imageView);
progressDialog = new ProgressDialog(this);
mstorage = FirebaseStorage.getInstance().getReference();
mUploadBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dispatchTakePictureIntent();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) {
Toast.makeText(this, "" + photoURI, Toast.LENGTH_SHORT).show();
progressDialog.setMessage("Uploading...");
progressDialog.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) {
Toast.makeText(DonationActivity.this, "Upload Successful!", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(DonationActivity.this, "Upload Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
String mCurrentPhotoPath;
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Ensure that there's a camera activity to handle the intent
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
} catch (IOException ex) {
// Error occurred while creating the File...
}
// Continue only if the File was successfully created
if (photoFile != null) {
photoURI = FileProvider.getUriForFile(this,
"com.example.android.fileprovider",
photoFile);
//takePictureIntent.setData(photoURI);
// takePictureIntent.putExtra("imageUri", photoURI.toString());
takePictureIntent.putExtra("imageUri", photoURI.toString());
// takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, CAMERA_REQUEST_CODE);
}
}
}
}
我在活动结果代码中得到的错误等于零。
答案 0 :(得分:0)
我的例子希望你理解它。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
Uri uri = data.getData();
progressDialog.setMessage(UPLOADING);
progressDialog.show();
StorageReference filePath = storageRef.child(STORAGE_FOLDER_NAME).child(recipeTitle.getText().toString());
filePath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(CreateNewRecipeActivity.this, UPLOAD_COMPLETE, Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
答案 1 :(得分:0)
BTW AFAIK,
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
如果你在Windows机器上,只需在RESULT_OK上按ctrl + B ** 所以,也许你在某种程度上取消活动,然后才能完成活动。我做了类似的事情。拍摄完视频/照片后,请等待操作系统显示勾选或其他内容以选择拍摄的照片。这是我的代码,如果它有帮助。
试试这个
/**
* Upload a video directly by recording it using camera
* You can do image/video whatever you require
*/
private void recordVideo() {
Intent recordVideoIntent = new Intent();
recordVideoIntent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
if (recordVideoIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(recordVideoIntent, UPLOAD_VIDEO_CAMERA);
}
}
//在Loader或异步任务中进行网络调用
getLoaderManager().initLoader(0, null, UploadVideo.this);
//在你的AsyncTask或Loader中,做这样的事情。您创建了一个重命名文件的功能。我猜不需要它。该文件会自动存储在手机AFAIK中。关于Firebase存储中文件的名称,只需使用类似这样的内容
//Upload the video to storage
StorageReference mFirebaseStorageRef = FirebaseStorage.getInstance().getReference();
mFirebaseStorageRef
.child(String.valueOf(mCurrentUser.getEmail() + new Date().getTime()))
.putFile(videoData).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
try {
//MAYBE UPDATE IT SOMEPLACE IN DATABASE AS WELL
HashMap<String, String> city_Obj = new HashMap<String,String>();
city_Obj.put("VIDEO_URL", downloadUrl);
city_Obj.put("VIDEO_NAME", nameOfVideo);
city_Obj.put("VIDEO_DESC", descriptionOfVideo);
dbRef.child("CITIES").child(spinnerCityName).push().setValue(city_Obj);
} catch (Exception e) {
e.printStackTrace();
Log.e("DB ERROR", e.getMessage());
}
答案 2 :(得分:0)
我正在捕捉图像,就像您在上传之前将图像保存到文件系统一样,但是使用 mCurrentPhotoPath 来加载位图。然后将位图转换为字节并从那里上传到Firebase存储。
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});
} else if (resultCode == RESULT_CANCELED) {
onCancel();
}
}
private File createImageFile() throws IOException {
String ts = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String filename = String.format("JPEG_%s_", ts);
File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(filename, ".jpg", storageDir);
mCurrentPhotoPath = image.getAbsolutePath();
return image;
}
要在我的应用程序中进一步细分,我首先在ImageView中显示图像,然后在上传时将其转换为byte [],就像这样。
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
然后上传到Firebase。
StorageReference reference = FirebaseStorage.getInstance().getReference().child("photo");
UploadTask uploadTask = reference.putBytes(imageBytes);
uploadTask.addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.d("UploadComplete", "Image successfully uploaded URL: %s", taskSnaphot.getDownloadUrl().toString());
}
});