Here I am using imagecropper dependency to crop and upload it to Firebase.
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == IMAGE_PICK_GALLERY_CODE) {
Uri image_uri = data.getData();
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//Updateprofilephoto(image_uri);
} else if (requestCode == IMAGE_PICK_CAMERA_CODE) {
//profileIv.setImageURI(image_uri);
CropImage.activity(data.getData())
.setGuidelines(CropImageView.Guidelines.ON)
.start(getActivity());
//uploadProfilePhoto(resulturi);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
Updateprofilephoto(resultUri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
My code works until this. I can crop the image by choosing an image from my gallery. But by using the following method I cannot upload my cropped image to the Firebase. The original image is uploaded to the Firebase. Not the cropped one. How can I solve that issue?
The code follows:
private void Updateprofilephoto(Uri resulturi) {
progressDialog.setMessage("Updating Account Info...");
progressDialog.setProgressStyle(progressDialog.STYLE_SPINNER);
progressDialog.show();
String filePathAndName = "profile_image/" + "" + firebaseAuth.getUid();
StorageReference storageReference = FirebaseStorage.getInstance().getReference(filePathAndName);
storageReference.putFile(resulturi)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful()) ;
Uri downloadImageUri = uriTask.getResult();
if (uriTask.isSuccessful()) {
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("profileImage", "" + downloadImageUri);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child(firebaseAuth.getUid()).updateChildren(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "Profile Picture is updated...", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(getActivity(), "" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
Related
I am quiet new to firebase and i'm trying to upload a image on firebase and whenever I try to upload It always say that uri is null. So I made a if condition if its null then it wont do the uploading.
I am quiet sure that the image is taking picture because I made a imageview so I can see the picture I've taken and its working properly
This is the code I use for my camera
private void askCameraPermissions() {
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.CAMERA}, CAMERA_PERM_CODE);
}
else
{
openCamera();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == CAMERA_PERM_CODE)
{
if (grantResults.length < 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}
else{
Toast.makeText(this, "Camera Permission Needed", Toast.LENGTH_SHORT).show();
}
}
}
private void openCamera() {
Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(camera, CAMERA_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST_CODE && data != null) {
imageuri = data.getData();
Bitmap image = (Bitmap) data.getExtras().get("data");
selfie.setImageBitmap(image);
Toast.makeText(getApplicationContext(), "Upload Success", Toast.LENGTH_SHORT).show();
}
}
And this is the code I use to upload Image
private void uploadPicture() {
if (imageuri != null) {
final ProgressDialog pd = new ProgressDialog(this);
pd.setTitle("Uploading...");
pd.show();
StorageReference riversRef = storageReference.child(System.currentTimeMillis() + ".jpg");
riversRef.putFile(imageuri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Snackbar.make(findViewById(android.R.id.content), "Attendance successful.", Snackbar.LENGTH_LONG).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
pd.dismiss();
Toast.makeText(getApplicationContext(), "Attendance Unsuccessful", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot snapshot) {
double progressPercent = (100.00 * snapshot.getBytesTransferred() / snapshot.getTotalByteCount());
pd.setMessage("Progress: " + (int) progressPercent + "%");
}
});
}
else{
Toast.makeText(getApplicationContext(), "Attendance Unsuccessful", Toast.LENGTH_SHORT).show();
}
}
I am following an android tutorial and I have been stuck on the deprecated method. I am unable to get the download url to enable me show the image in an ImageView
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE_RESULT && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
StorageReference ref = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
ref.putFile(imageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String url = taskSnapshot.getDownloadUrl().toString();
String pictureName = taskSnapshot.getStorage().getPath();
deal.setImageUrl(url);
How can I modify the line "String url = taskSnapshot.getDownloadUrl().toString();" so that I can be able to get the download link?
getDownloadUrl() is deprecated so you need to use Task and check isComplete() like below to see if it is completed
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICTURE_RESULT && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
StorageReference ref = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
ref.putFile(imageUri).addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl();
while(!uri.isComplete());
Uri url = uri.getResult();
Log.i(TAG, url.toString());
deal.setImageUrl(url.toString());
Try this
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
Try this
StorageReference imageRef = FirebaseUtil.mStorageRef.child(imageUri.getLastPathSegment());
UploadTask uploadTask = imageRef.putFile(imageUri);
uploadTask.continueWithTask(task -> {
if (!task.isSuccessful()) {
if (task.getException() != null)
throw task.getException();
}
return imageRef.getDownloadUrl();
}).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult()
} else {
if (task.getException() != null)
task.getException().printStackTrace();
}
});
i am uploading video to firebase storage. i want to show the thumbnail of selected video on app screen
i have tried uploading image with the same code and it gives me the image preview of selected image, but it doesnot show any preview or thumbnail of selected video
moreover i want to know hoe to give the path of selected video as well..
main activity
public class MainActivity extends AppCompatActivity {
private static final int PICK_VIDEO_REQUEST = 3;
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://<<ur app url>>"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("video/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Video"), PICK_VIDEO_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("vide.mp4");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select a video", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
I am trying to build a replace profile picture functionality in my code using the codes below.It works fine sometimes.Other times, nothing happens after i select the picture from my gallery(Some images).It appears the select image from gallery activity just crashes after i select the image to upload and the application just terminates in logcat without any error.It used to work fine before i added the progress dialog
private void postImage() {
String path = "userProfiles/" + UUID.randomUUID() + ".jpeg";
StorageReference userProfilesRef = storage.getReference(path);
userProfilesRef.putFile(resultUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
downloadUrls = taskSnapshot.getDownloadUrl().toString();
Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
final String id = firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.child("Male").hasChild(id)){
databaseReference.child("Male").child(id).child("downloadUrl").setValue(downloadUrls);
databaseReference1.child("Male").child(key).child("downloadUrl").setValue(downloadUrls);
}
else {
databaseReference.child("Female").child(id).child("downloadUrl").setValue(downloadUrls);
databaseReference1.child("Female").child(key).child("downloadUrl").setValue(downloadUrls);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Toast.makeText(getApplicationContext(), " Uploaded ", Toast.LENGTH_LONG).show();
}
});
}
});
/* userProfilesRef.putFile(filePath).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), " Upload Failed, Please try again ", Toast.LENGTH_LONG).show();
//progressDialog.dismiss();
}
});*/
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
CropImage.activity(filePath)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog.setMessage("Uploading Please Wait...");
mProgressDialog.show();
resultUri = result.getUri();
postImage();
image.setImageURI(resultUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
try to add
if(mProgressDialog != null)
mProgressDialog.dismiss();
if there is no error so you miss something at your dialog declaration
I am trying to upload Image to firebase storage but I am neither seeing the progress dialog nor the toast message.
The debug breakpoint is not even stopping at those lines.
Please help.
ib_profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent_modifyImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivity(intent_modifyImage);
}
});
}
//Image Capture Activity Result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK){
progressDialog.setMessage("Uploading Image...");
progressDialog.show();
Uri uri = data.getData();
StorageReference filepath = storageReference_image.child("profile_photos").child(uri.getLastPathSegment());
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(UserProfileActivity.this,"Upload Complete",Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
});
}
}
try this
public class MainActivity extends AppCompatActivity {
Button chooseImg, uploadImg;
ImageView imgView;
int PICK_IMAGE_REQUEST = 111;
Uri filePath;
ProgressDialog pd;
//creating reference to firebase storage
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://fir-example-c4312.appspot.com"); //change the url according to your firebase app
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chooseImg = (Button)findViewById(R.id.chooseImg);
uploadImg = (Button)findViewById(R.id.uploadImg);
imgView = (ImageView)findViewById(R.id.imgView);
pd = new ProgressDialog(this);
pd.setMessage("Uploading....");
chooseImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK);
startActivityForResult(Intent.createChooser(intent, "Select Image"), PICK_IMAGE_REQUEST);
}
});
uploadImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(filePath != null) {
pd.show();
StorageReference childRef = storageRef.child("image.jpg");
//uploading the image
UploadTask uploadTask = childRef.putFile(filePath);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload successful", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Upload Failed -> " + e, Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(MainActivity.this, "Select an image", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
//getting image from gallery
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting image to ImageView
imgView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
don't forget to Change Rules in firebase console
By default we are not allowed to access firebase storage without authentication. To change it go to firebase console using any web browser. Open the firebase project that you have used in above steps and go to Storage and then Rules tab. Now change read and write rules to true as shown in below image.
try this method,its worked for me
Inside onActivityResult,
StorageReference storageRef = storage.getReferenceFromUrl(---STORAGE_BUCKET---);
StorageReference imagePathReference = storageRef.child("image");
final Uri uri = data.getData();
Bitmap bmp = null;
try {
bmp = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
// convert bitmap to byte array to save image in firebase storage
ByteArrayOutputStream bos = new ByteArrayOutputStream();
if (bmp != null) {
bmp.compress(Bitmap.CompressFormat.JPEG, 60, bos);
}
byte[] dataNew = bos.toByteArray();
uploadTask = imagePathReference.putBytes(dataNew);
try {
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// success
}
});
}catch (Exception e){
}