I tried to share the image in my chat application. But was not able to successfully share it. It's selecting the image from the gallery but not appearing in the Userchat screen and not getting upload in the firebase also.
I am not able to find the solution for it. I would very much appreciate if someone can help me out.
attachment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CharSequence options[] = new CharSequence[]
{
"Image", "Documents"
};
AlertDialog.Builder builder = new AlertDialog.Builder(UserChatActivity.this);
builder.setTitle("Select File");
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(i == 0)
{
checker = "image";
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent.createChooser(intent, "Select Image"), 438);
}
if (i == 1)
{
checker = "pdf";
}
}
});
builder.show();
}
});
StorageReference
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && requestCode == RESULT_OK && data != null && data.getData() != null)
{
fileUri = data.getData();
if (!checker.equals("image"))
{
}
else if (checker.equals("image"))
{
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image Files").child(fAuth.getUid());;
}
else
{
Toast.makeText(this, "Nothing Selected", Toast.LENGTH_SHORT).show();
}
}
}
Store that image URL in your chat.
You can do something like this, I am giving you an example for firebase realtime database:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 438 && resultCode == RESULT_OK && data != null && data.getData() != null) {
// you should show some progress dialog or progress bar here for better user experience.
progressDialog.show()
fileUri = data.getData();
if (checker.equals("image")) {
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Image files");
final String messgSenderRef = "Messages/" + mAuth.getCurrentUser().getUid() + "/" + userId;
final String messgReceiverRf = "Messages/" + userId + "/" + mAuth.getCurrentUser().getUid();
DatabaseReference messageRef = databaseReference.child("Messages").child(mAuth.getCurrentUser().getUid()).child(userId).push();
final String messagePushId = messageRef.getKey();
final StorageReference filepath = storageReference.child(messagePushId + "." + "jpg");
filepath.putFile(fileUri).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull UploadTask.TaskSnapshot taskSnapshot) {
// you can show progress of upload here, let suppose you have a progressDialog then:-
double p = ((double) 100 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
progressDialog.setMessage((int) p + "%" + " Uploading....");
}
}).continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
progressDialog.dismiss();
// Now you have Uri of your image
downloadUri = task.getResult().toString();
Map<String, Object> messageTextBody = new HashMap<>();
messageTextBody.put("message", downloadUri);
messageTextBody.put("name", fileUri.getLastPathSegment());
messageTextBody.put("type", fileStatus);
messageTextBody.put("from", mAuth.getCurrentUser().getUid());
messageTextBody.put("to", userId);
messageTextBody.put("messageId", messagePushId);
messageTextBody.put("time", saveCurrentTime);
messageTextBody.put("date", saveCurrentDate);
Map<String, Object> messageBodydetails = new HashMap<>();
// add message to sender and receiver's
messageBodydetails.put(messgSenderRef + "/" + messagePushId, messageTextBody);
messageBodydetails.put(messgReceiverRf + "/" + messagePushId, messageTextBody);
databaseReference.updateChildren(messageBodydetails).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
editText.setText("");
}
}
});
} else {
Toast.makeText(ChatActivity.this, "Error: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
} else {
}
}
}
Then in the chat you can check for the changes in the database in realtime and update your chat's recycler view in realtime. Just specify the chat message type to identify and display the view accordingly. If the chat type is text, show the text message. If the chat type is an image, load an image from the URL you have stored.
Related
I am learning to write in java.
I registered a photo transfer method Using the Cropimage library for cropping photos. Preparing photos for transfer
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK && data != null) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
imageUriPts = result.getUri();
} else {
Toast.makeText(this, "Произошла ошибка", Toast.LENGTH_SHORT).show();
}
}
The transfer method
private void loadImagePts() {
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Идет загрузка");
progressDialog.setMessage("Пожалуйста подождите");
progressDialog.show();
if (imageUriPts != null) {
final StorageReference fileRef = storageDeliveryPts.child(mAuth.getCurrentUser().getUid() + "jpg");
uploadTask = fileRef.putFile(imageUriPts);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()) {
throw task.getException();
}
return fileRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
myUri = downloadUri.toString();
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("uid", mAuth.getCurrentUser().getUid());
userMap.put("image", myUri);
PtsRef.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
progressDialog.dismiss();
startActivity(new Intent(PTSActivity.this, HomeActivity.class));
}
}
});
}
}
There are two imageviews where photos are added and one upload button. which should launch the method of loading two photos at onсе.what does it look like visually
PtsRef is DatabaseReference MyUri is String MyUri=''
How to make it possible to post two photos with one activity?
Tried creating a second empty string but didn't work.
I read different articles on how to go about it and i use a particularly easy one that i have no idea why i did not think of that in the first place, It was to loop the method that contains the function of uploading a "single image", looping it will then repeat the method according to the number of images to be uploaded, but i am finding something rather troubling here, maybe its my code or something but i have no idea why, during the loop, it loops according to the number of images alright, but when i check the firebase storage, i find just an image at the directory which is always the last image i selected, so i am thinking maybe my code deletes existing images in the directory and then save incoming images therefore deleting all previous images and leaving only the last one ( just a thought though) i am attaching my code now, i am so sorry, but i sometimes make mistakes in attaching codes, please bear with me.
The OnActivityResult method:
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == gallerypick && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
Toast.makeText(this, "multiple images selected", Toast.LENGTH_SHORT).show();
count = data.getClipData().getItemCount();
for (i = 0; i < count; i++) {
imageuri = data.getClipData().getItemAt(i).getUri();
inputproductimg.setImageURI(data.getClipData().getItemAt(0).getUri());
}
} else {
if (data.getData() != null) {
Toast.makeText(this, "Single image selected", Toast.LENGTH_SHORT).show();
imageuri = data.getData();
inputproductimg.setImageURI(imageuri);
}
}
}
}
method that calls the upload image function
addproductbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Validateproduct();
}
});
}
private void Validateproduct() {
Pname = inputproductname.getText().toString();
Pdescription = inputproductdesc.getText().toString();
Pprice = inputproductprice.getText().toString();
if (imageuri == null) {
Toast.makeText(this, "One image must be selected at least", Toast.LENGTH_SHORT).show();
} else {
if (TextUtils.isEmpty(Pname) || TextUtils.isEmpty(Pdescription) || TextUtils.isEmpty(Pprice)) {
Toast.makeText(this, "Please fill out all fields", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Images will take turns to save, Please wait...", Toast.LENGTH_SHORT).show();
for (i = 0; i < count; i++) {
storeproductinfo(imageuri, i);
}
}
}
}
and the upload image function itself
private void storeproductinfo(Uri imageuri, int i) {
Calendar calender = Calendar.getInstance();
SimpleDateFormat currentdate = new SimpleDateFormat("MMM dd, yyyy");
savecurrentdate = currentdate.format(calender.getTime());
SimpleDateFormat currenttime = new SimpleDateFormat("HH:mm:ss a");
savecurrenttime = currenttime.format(calender.getTime());
productkey = savecurrentdate + savecurrenttime;
final StorageReference filepath = Pimagesref.child(gendercategoryname).child(categoryname)
.child(Pname + productkey).child(this.imageuri.getLastPathSegment() + gendercategoryname + categoryname + productkey + ".jpg");
progressbar.setVisibility(View.VISIBLE);
final UploadTask uploadTask = filepath.putFile(this.imageuri);
filepath.putFile(this.imageuri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
String message = e.toString();
progressbar.setVisibility(View.INVISIBLE);
Toast.makeText(newProduct.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressbar.setVisibility(View.INVISIBLE);
Toast.makeText(newProduct.this, "Image uploaded successfully", Toast.LENGTH_SHORT).show();
Task<Uri> urltask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful()) {
progressbar.setVisibility(View.INVISIBLE);
throw task.getException();
}
downloadUrl = filepath.getDownloadUrl().toString();
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(#NonNull Task task) {
if (task.isSuccessful()) {
downloadUrl = task.getResult().toString();
progressbar.setVisibility(View.INVISIBLE);
Toast.makeText(newProduct.this, "Product Image URL has been created", Toast.LENGTH_SHORT).show();
Saveproductinfo();
}
}
});
}
});
}
maybe the upload method wasnt necessary but im only being thorough, please kindly help in pointing out my mistake(s)
Thank you.
Here's what I have been able to get so far. After selecting the images
selectImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask != null && mUploadTask.isInProgress()){
Toast.makeText(MainActivity.this, "Upload In Progress", Toast.LENGTH_SHORT).show();
}
else {
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), RESULT_LOAD_IMAGE);
}
}
});
Inside the OnActivityResult, I am uploading my selected Images to the Firebase Storage and at the same time I want to store my download Urls of those multiple images to the Firebase Firestore
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
final String[] downloadUrl = new String[1];
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
int totalItemsSelected = data.getClipData().getItemCount();
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = storageReference.child("Images").child(fileName);
final int finalI = i;
final int totalCount = totalItemsSelected;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
storeLink(url,totalCount);//Method To Store the Url
}
});
// Toast.makeText(add_for_sale.this, "Uploading works", Toast.LENGTH_SHORT).show();
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
// ImageUploadInfo imageUploadInfo = new ImageUploadInfo(downloadUrl[0],fileName);
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
}
In the method storeLink(url,totalCount), I am creating a map object to create field "imageUrl" inside the document,where "29t0Boxm0fa8UNkomuo5xPLwkx13" is a user id.
private void storeLink(final String url,final int totalCount) {
FirebaseFirestore storeUrl = FirebaseFirestore.getInstance();
Toast.makeText(MainActivity.this, url, Toast.LENGTH_LONG).show();
for (int i=0;i<totalCount;i++) {
final Map<String, Object> image = new HashMap<>();
image.put("imageUrl"+i, url);
DocumentReference documentReference = storeUrl.collection("users").document("29t0Boxm0fa8UNkomuo5xPLwkx13");
documentReference.set(image).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "" +
"OnSuccess : Image Link Saved ");
// startActivity(new Intent(Register.this,LoginActivity.class));
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "OnFailure : " + e.toString());
}
});
}
}
Storage Rules
rules_version = '2'
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
Firestore Rules
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
Make sure you have made final to Map<String,Object> user = new HashMap<>();
And add user.put("key","value") inside the loop.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final DocumentReference documentReference = db.collection("users").document("multi_image");
final Map<String, Object> user = new HashMap<>();
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK) {
if (data.getClipData() != null) {
final int totalItemsSelected = data.getClipData().getItemCount();
for (int i = 0; i < totalItemsSelected; i++) {
Uri fileUri = data.getClipData().getItemAt(i).getUri();
final int x = i;
final StorageReference fileToUpload = mStorageRef.child("Images").child("" + x);
fileToUpload.putFile(fileUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> DownloadURL = taskSnapshot.getStorage().getDownloadUrl();
DownloadURL.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
user.put("image_" + x, uri.toString());
Log.v("users", "" + user);
documentReference.update(user)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.v("task", "Success");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.v("failed", "" + e);
}
});
}
});
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
} else if (data.getData() != null) {
Toast.makeText(this, "Selected Single", Toast.LENGTH_SHORT).show();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
Firebase Storage https://i.stack.imgur.com/HeYvh.png
Firebase Database https://i.stack.imgur.com/3t2aN.png
Here's what worked out for me finally :
Create an ArrayList variable globally
ArrayList<String> imageList;
Then initialize this ArrayList inside the
onActivityResult as imageList = new ArrayList<>(totalItemsSelected); as mentioned inside the code below
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String fileName;
if(requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK){
if(data.getClipData() != null){
progressBar.setVisibility(View.VISIBLE);
final int totalItemsSelected = data.getClipData().getItemCount();
count = totalItemsSelected;
imageList = new ArrayList<>(totalItemsSelected);
StorageReference ImageFolder = FirebaseStorage.getInstance().getReference().child("ImageFolder");
for(int i =0;i<totalItemsSelected;i++){
Uri fileUri = data.getClipData().getItemAt(i).getUri();
fileName = getFileName(fileUri);
fileNameList.add(fileName);
fileDoneList.add("uploading");
uploadListAdapter.notifyDataSetChanged();
final StorageReference fileToUpload = ImageFolder.child(fileName);
final int finalI = i;
mUploadTask = fileToUpload.putFile(fileUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressBar.setVisibility(View.INVISIBLE);
fileToUpload.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
imageList.add(url);
// Toast.makeText(add_for_sale.this, imageList.get(finalI), Toast.LENGTH_SHORT).show();
Log.i(TAG,"Added To List");
}
});
fileDoneList.remove(finalI);
fileDoneList.add(finalI,"done");
uploadListAdapter.notifyDataSetChanged();
}
});
}
Toast.makeText(this, "Upload in Progress", Toast.LENGTH_SHORT).show();
}
else if(data.getData() != null){
Toast.makeText(this, "Select Two or More Images", Toast.LENGTH_SHORT).show();
}
}
}
Now to Save the Url Links to the Firebase Firestore Add the links to the ArrayList as imageList.add(url;)
and upload this list imageList to the FireStore as
Map<String,Object> imageUrl = new HashMap<>();
imageUrl.put("ImageUrl", imageList);
String userId;
userId = firebaseUser.getUid();
firebaseFirestore.collection("ImageDetails").document(userId)
.set(imageUrl,SetOptions.merge());
This will create an array of ImageUrl inside your firestore document
I am trying to utilise an image cropper (from ArthurHub GitHub) getting an error when typing getDownloadURL() i have put getStorage() in front using the getStorage() gets rid of the red line under getDownloadUrl however when I press crop I get the error message I have coded down the very end of this piece of code 'image cannot be cropped'. Does anyone know how to fix this
/*...*/ {
ProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, Gallery_Pick);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==Gallery_Pick && resultCode==RESULT_OK && data!= null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1,1)
.start(this);
}
if(requestCode==CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if(requestCode == RESULT_OK)
{
loadingBar.setTitle("Profile Image");
loadingBar.setMessage("Please wait while we are updating your profile image");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImageRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
Toast.makeText(SetupActivity.this, "Profile image stored successfully to firebase storage", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
UsersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if(task.isSuccessful())
{
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "Profile Image stored to firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error occurred:" + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
}
else
{
Toast.makeText(this, "Error Occurred: Image can't be cropped try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}
If i give to the Picasso's load() method any photo url as parameter, the photo uploads, but when i give the load() method the parameter "image" as you can see in following code, the image is not displayed on the android device. The device displays the placeholder.
Also, the downloadUrl string form the onActivityResult() method is the same as the one from the image string.
Please help!
currentUserId = mAuth.getCurrentUser().getUid();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users").child(currentUserId);
profileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, galleryPick);
}
});
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
if(dataSnapshot.hasChild("profileimage")){
String image = dataSnapshot.child("profileimage").getValue().toString();
//Glide.with(SetupActivity.this).load(image).placeholder(R.drawable.profile).into(profileImage);
Picasso.get().load(image).placeholder(R.drawable.profile).into(profileImage);
} else {
Toast.makeText(SetupActivity.this, "Please select profile image first...", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == galleryPick && resultCode == RESULT_OK && data!=null){
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.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){
loadingBar.setTitle("Profile image");
loadingBar.setMessage("Please wait, while we're updating your profile image...");
loadingBar.show();
loadingBar.setCanceledOnTouchOutside(true);
Uri resultUri = result.getUri();
StorageReference filePath = userProfileImageRef.child(currentUserId + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
Toast.makeText(SetupActivity.this, "Profile image successfully stored in Firebase database...", Toast.LENGTH_SHORT).show();
final String downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
usersRef.child("profileimage").setValue(downloadUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Intent selfIntent = new Intent(SetupActivity.this, SetupActivity.class);
startActivity(selfIntent);
Toast.makeText(SetupActivity.this, "Profile image stored to Firebase database successfully", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else{
String message = task.getException().getMessage();
Toast.makeText(SetupActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
});
} else {
Toast.makeText(this, "Error occured: Image can't be cropped. Try again!", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}