I'm trying to upload an image from Gallery to Firebase Storage.
Picking an Image from the Gallery works fine but then the selected Image is not being uploaded to Firebase Storage.
I think the problem is with this module in my code which I'm not able to figure out.
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at photos/<FILENAME>
StorageReference photoRef = mPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
//Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
#SuppressWarnings("VisibleForTests")
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Message message = new Message(null, userName, downloadUrl.toString());
messagesDatabaseReference.push().setValue(message);
}
});
I'm running my app on my mobile device Moto G4 (Android Nougat) through USB.
In my OnActivityResult, I modified the following:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
....
} else if (resultCode == RESULT_CANCELED) {
....
}
} else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
}
}
Related
In my activity how can I use two select buttons in same activity to select files from internal storage and upload on database using same upload button
Yes. Just you need do on onActivityResult put upload button method when is selected file. It's gonna upload straight file when it's selected.
Look at this
public void choosefile() {
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
Intent cInt = new Intent(MediaStore.ACTION_GET_CONTENT);
cInt.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(output));
startActivityForResult(cInt,100);
}
and on result
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
upload(media_path);
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity(), "Cancelled front", Toast.LENGTH_LONG).show();
}
}
}
how to open only camera and crop using theartofdev dependency .I am using theartofdev dependency 2.7.+ .
Try this
//Declare in Manifest file
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat" />
// Declare global variable
Uri mCropImageUri;
// write below line on the button click
CropImage.startPickImageActivity(this);
// then result will received inside onActivityResult() method
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
getImageCallback(requestCode,resultCode,data);
}
public void getImageCallback(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
} else {
// no permissions required or already grunted, can start crop image activity
startCropImageActivity(imageUri);
}
}
else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
profileImage.setImageURI(resultUri);
}
}
}
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri).setGuidelines(CropImageView.Guidelines.ON).setCropShape(CropImageView.CropShape.OVAL).start(this);
}
I am using the Android-Image-Cropper library. It seems to work fine with pictures taken with the camera itself, but when I select images from the gallery that were downloaded from the internet and crop them, the image does not completely cover the ImageButton.
Here is a picture of it not working (downloaded)
Here is one that is working (taken with camera)
Here is my code from the activity:
public void setProfilePicture(View view) {
CropImage.startPickImageActivity(this);
}
#Override
#SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// handle result of pick image chooser
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage.
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
} else {
// no permissions required or already granted, can start crop image activity
startCropImageActivity(imageUri);
}
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
profilepicture.setImageURI(resultUri);
} else if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception e = result.getError();
}
}
}
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// required permissions granted, start crop image activity
startCropImageActivity(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
}
private void startCropImageActivity(Uri imageUri) {
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.start(this);
}
}
Oh wait it figured it out.
I had to set android:scaleType="fitCenter" in my XML and
.setAspectRatio(1, 1)
.setFixAspectRatio(true)
to my startCropImageActivity method.
This is the my code ( check this file full code on GitHub) for Uploading an image to Firebase Storage.
// ImagePickerButton shows an image picker to upload a image for a message
mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setType("image/*");
i.setAction(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(i, "Complete action using"), RC_PHOTO_PICKER);
}
});
This is the OnActivityResult Method:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
//get the reference to stored file at database
StorageReference selectedImageFilePath = mStorageReference.child(selectedImageUri.getLastPathSegment());
//upload file to firebase
selectedImageFilePath.putFile(selectedImageUri).addOnSuccessListener(MainActivity.this, new OnSuccessListener < UploadTask.TaskSnapshot > () {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
#SuppressWarnings("VisibleForTests")
String downloadUrl = taskSnapshot.getDownloadUrl().toString();
Message message = new Message(null, userName, downloadUrl);
messagesDatabaseReference.push().setValue(message);
}
});
}
}
}
Picking an Image from the Gallery works fine but I'm not able to upload the selected Image on Firebase Storage. Correct my code If I'm wrong at any site. However, I manually entered these lines in my manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I'm currently running the app in my own mobile device connected via USB( Moto G4 - Nougat)
data.getData() could return an URI that does not point to a File.
You should use
InputStream is = getContentResolver().openInputStream(data.getData())
and than use
selectedImageFilePath.putStream(is)
Also you could add an onFailureListener to the upload task and debug what is going wrong.
In addition, if I recall correctly, I do not think you need the storage permissions when you directly read the data in onActivityResult.
Try this for button click :
//Select Image functionality
btnselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
});
For saving image to fire base :
//Storing and getting image from firebase
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
final Uri uri = data.getData();
StorageReference filepath = mStorageRef.child("Photos").child(name);
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
//Getting url where image is stored
saveImage(downloadUri);
Picasso.with(getActivity()).load(downloadUri).fit().centerCrop().into(profileImage);
}
});
}
This works fine for me, Hope this will help.
Instead of else if statement, I modified it by writing a seperate if statement.
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
}else if (resultCode == RESULT_CANCELED) {
}
// This was the change I made
if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
}
}
If ( //sign in)
{
If (//result ok)
{}
else if (//result cancel)
{}
}
else if (//rc photot picker && result ok)
{ //your storage code here.....}
tats works perfectly.....check out the braces carefully....
I'm trying to upload a picture taken from the camera and I got Nullpointer exception, here its the code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT && resultCode == RESULT_OK){
uri= data.getData();
mImagenIv.setImageURI(uri);
StorageReference filepath = mStorage.child("fotos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"si señor",Toast.LENGTH_LONG).show();
}
});
} else if(requestCode == CAMERA_INTENT && resultCode == RESULT_OK){
Bitmap bitmap = (Bitmap) data.getExtras().get("data");
Uri uri= data.getData();
mImagenIv.setImageBitmap(bitmap);
StorageReference filepath = mStorage.child("fotos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(),"si señor",Toast.LENGTH_LONG).show();
}
});
}
}
The thing its that when I use the same code when I select a picture from the storage that code its working as expected.The null pointer I got its on the following line:
StorageReference filepath = mStorage.child("fotos").child(uri.getLastPathSegment());
Could someone helpme with that?
Assuming that the startActivityForResult() call for CAMERA_INTENT is using ACTION_IMAGE_CAPTURE, data.getData() should always return null. If Bitmap bitmap = (Bitmap) data.getExtras().get("data"); is working, that Bitmap is your photo. You will need to get that to Firebase by one means or another. If the Firebase API does not accept a Bitmap, you may have to use compress() to write that Bitmap to some temporary file to use with Firebase.