Reputation: 79
I am capturing images by using camera and want to send to firebase storage. But I am getting error by 3 three days. I am stuck on it. When I fire intent it captures image, but in onActivityresult it returns request code=1 and result code=-1. Here is my code
Donation Activity:
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);
}
}
}
}
I am getting error in activity resultcode that is equal to zero.
Upvotes: 0
Views: 3051
Reputation: 419
I am capturing the image just as you are with saving the image to the file system before uploading, but using the mCurrentPhotoPath to load the Bitmap instead. Then convert the Bitmap to bytes and upload to Firebase Storage from there.
@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;
}
To break it down further in my application I am first displaying the image within an ImageView and then when uploaded converting it to byte[] like this.
Bitmap bitmap = ((BitmapDrawable) mImageView.getDrawable().getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
And then upload to 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());
}
});
Upvotes: 1
Reputation: 147
BTW AFAIK,
public static final int RESULT_OK = -1;
public static final int RESULT_CANCELED = 0;
Just press ctrl + B on RESULT_OK if you are on Windows machine** So maybe you are somehow cancelling activity the activity before it gets completed. I have done something similar. After your video/photo is taken, wait for the OS to display a tick or something to select that picture taken. Here is my code if it helps.
Try this
/**
* 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);
}
}
//Make the network call in a Loader or Async Task
getLoaderManager().initLoader(0, null, UploadVideo.this);
//And inside your AsyncTask or Loader, do something like this. You made a function to rename your file. It is not needed I guess. The file is stored automatically in your phone AFAIK. And regarding the name of file in Firebase STorage, just use something like this
//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());
}
Upvotes: 0
Reputation: 426
My example hope you understand it.
@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();
}
});
}
}
Upvotes: 0