Update and Delete documents from two different collections on single click - android

I'm creating an app like olx, Where if you upload ad , its gets posted in two different collections, namly "My Ads" where ads of every logged in user are posted against his ID, and Explore collection Where ads are posted for all users. So if i want to update or delete ad, It should be deleted from both collections! Image Url :https://imgur.com/a/HCKfGBb
String uid= user.getUid();
SellingDetails.put("uid",uid);
final CollectionReference reference = exploreAdDB.collection("cities/" + city + "/" + category);
final CollectionReference myAdDocRef = myAdDB.collection("users/ads/"+uid);
if (imageUri != null) {
final StorageReference fileReference = mStorage.child(System.currentTimeMillis()
+ "." + getFileExtension(imageUri));
UploadTask uploadTask = fileReference.putFile(imageUri);
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()) {
throw task.getException();
}
return fileReference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
if(downloadUri!=null)
SellingDetails.put("imageUrl",downloadUri.toString());
reference.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Service Uploaded in explore db ", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
Intent intent = new Intent(GetLocationActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
Toast.makeText(GetLocationActivity.this, "Ad posted Successfully", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Failed adding data into explore db", Toast.LENGTH_SHORT).show();
pgAd.setVisibility(View.INVISIBLE);
}
});
myAdDocRef.add(SellingDetails).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(GetLocationActivity.this, "Data Also added to myAds db", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(GetLocationActivity.this, "Data not added into my ads", Toast.LENGTH_SHORT).show();
}
});
} else {
// Handle failures
Toast.makeText(GetLocationActivity.this, "Failed adding data", Toast.LENGTH_SHORT).show();
}
}
});
}

Related

getting same URL when uploading to firebase storage - Android

Whenever I'm trying to upload a file to firebase storage, and then retrieve the download URL for it, I'm getting the same URL even when different files are uploaded. The files do get uploaded, but the URL received is similar for every upload
downloadURL = new Uri[1];
UploadTask uploadTask = mChatPhotosStorageReference
.child(selectedImageUri.getLastPathSegment())
.putFile(selectedImageUri);
Log.v("SelectedImage: ", selectedImageUri.getLastPathSegment());
uploadTask
.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 mChatPhotosStorageReference.getDownloadUrl();
}
})
.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
downloadURL[0] = task.getResult();
//passing downloadUri to database to store with chat messages
ShutUpMessages shutUpMessages = new ShutUpMessages(null, mUsername, downloadURL[0].toString());
mMessagesDatabaseReference.push().setValue(shutUpMessages);
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
Toast.makeText(MainActivity.this, "File Uploaded", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(MainActivity.this, "File Upload failed", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Toast.makeText(MainActivity.this, exception.getMessage(), Toast.LENGTH_SHORT).show();
mProgressbar.setVisibility(ProgressBar.INVISIBLE);
}
});

Why isn't my image showing when retrieved from Firebase eventhough it was successfully uploaded?

This is my code.
private void uploadPattern() {
if (mImageUri != null) {
final StorageReference fileReference = mStorageRef.child(System.currentTimeMillis() + "." + getFileExtension(mImageUri));
mUploadTask = fileReference.putFile(mImageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
mProgressBar.setProgress(0);
}
}, 500);
Toast.makeText(PatternArranger.this, "Save Successful", Toast.LENGTH_SHORT).show();
//Upload upload = new Upload(mEditPatternName.getText().toString().trim(),
//taskSnapshot.getUploadSessionUri().toString());
//String uploadId = mDatabaseRef.push().getKey();
//mDatabaseRef.child(uploadId).setValue(upload);
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//Log.d(TAG, "onSuccess: firebase download url: " + downloadUrl.toString()); //use if testing...don't need this line.
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUrl.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(PatternArranger.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
mProgressBar.setProgress((int) progress);
}
});
} else {
Toast.makeText(this, "No pattern selected", Toast.LENGTH_SHORT).show();
}
}
By using a while loop, you are likely missing out on important debugging information to solve your issue. In your code, it is likely that urlTask has failed and urlTask.isSuccessful() will never evaluate to true which is causing an infinite loop.
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while ( !urlTask.isSuccessful());
To fix this, properly attach listeners to the Task returned by each operation and log their results.
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUri) {
Log.d(TAG, "getDownloadUrl.onSuccess: obtained download URI: " + downloadUri.toString());
Upload upload = new Upload(mEditPatternName.getText().toString().trim(),downloadUri.toString());
String uploadId = mDatabaseRef.push().getKey();
mDatabaseRef.child(uploadId).setValue(upload)
.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess() {
Log.d(TAG, "setValue.onSuccess: uploaded & saved to database");
// TODO: Update UI to show image/completion message
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "setValue.onFailure: error occured - " + exception.message);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Log.d(TAG, "getDownloadUrl.onFailure: error occured - " + exception.message);
}
});

Cannot Delete An Image From Firebase Storage

I am trying to replace an image in Firebase storage with a new one by first deleting the old and then adding the new. The problem is the deletion. I cannot seem to get it to work. Here is the relevant code:
private void uploadFile(){
progressBar.setVisibility(View.VISIBLE);
db2 = FirebaseFirestore.getInstance().collection("Users").document(id);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
StorageReference fileReference = storageReference.child(System.currentTimeMillis()
+ "."+ getFileExtension(imageuri));
mUploadTask = fileReference.putFile(imageuri).
addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
db2.update("Image URI",downloadUrl.toString()).addOnSuccessListener(
new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(settings_activity
.this, "DP change added." ,
Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
}
).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FIRESTROE ERROR "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "FILE STRORAGE "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(settings_activity.this, "DELETION ERROR: "+e.getMessage(), Toast.LENGTH_SHORT).show();
progressBar.setVisibility(View.GONE);
}
});
}
This is the storage reference I used in the code above:
FirebaseStorage.getInstance().getReference().child("profile_pics/"+FirebaseAuth.getInstance().getCurrentUser().getUid());

How to get Firebase Storage image URL in android studio?

I want to display image on imageView from Firebase Storage without saving the picture in the device, so I've tried to use the highlighted URL (from the photo below) and it works but I don't want to write the address manually.
How can I get the address using the code?
p.s I tried dataBaseStorageRef.getDownloadUrl() and it gives me another URL, not the one from the picture.
enter image description here
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
final StorageReference filePath = storage.child("books").child(""+AddBook.book_id+1).child("photo.jpg");
if(requestCode == RESULT_GALLERY){
if (resultCode == RESULT_OK){
pic_uri = data.getData();
book_img.setImageURI(pic_uri);
filePath.putFile(pic_uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(AddBookActivity.this, "Upload done", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(AddBookActivity.this, "Failed to upload!", Toast.LENGTH_SHORT).show();
}
});
img_addr = filePath.getDownloadUrl().toString();
Toast.makeText(this, "picture was selected", Toast.LENGTH_SHORT).show();
}
}
}
Then, I'm trying to display the pic from img_addr from another activity
and it doesn't work because the address of image_addr is not good (if I replace manually img_addr to the address from the attached link it works)
if(books_list.get(i).img_addr!=null){
Toast.makeText(v.getContext(),books_list.get(i).img_addr,Toast.LENGTH_LONG).show();
Picasso.with(v.getContext()).load(books_list.get(i).img_addr).resize(50,50).into(img);
}
Thanks to those who help
You can use continueWithTask method to return the download url
Like the following:
final UploadTask uploadTask = filepath.putFile(uri);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
uploadTask.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();
}
// Continue with the task to get the download URL
return filepath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
thumb_download_url = task.getResult().toString();
}
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
Make getDownloadUrl() asynchronous by adding onsuccess and onfailure listeners to it.
Your complete image upload task should look like below
photoReference.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
photoReference.getDownloadUrl().addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//do something
}
}).addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//get your image uri here
Uri imgUrl = uri;
String imgStringUrl = imgUrl.toString();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// do something
}
});
You can get download URL from below method:
private void uploadToStorage(String imgPath, String fileName) {
Uri file = Uri.fromFile(new File(imgPath));
StorageReference storageReference = mStorageRef.child(userId + "/images/" + fileName);
storageReference.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> downloadUrl = taskSnapshot.getStorage().getDownloadUrl();
downloadUrl.addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
Log.v(TAG, "Media is uploaded");
String downloadURL = "https://" + task.getResult().getEncodedAuthority()
+ task.getResult().getEncodedPath()
+ "?alt=media&token="
+ task.getResult().getQueryParameters("token").get(0);
Log.v(TAG, "downloadURL: " + downloadURL);
//save your downloadURL
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.v(TAG, "Media is not uploaded");
Log.v(TAG, "Exception: " + exception.getLocalizedMessage());
}
});
}
You can also get scheme name & query from methods under task.getResult()

Android Firebase "UserProfileChangeRequest" is working, but not after user sign out and sign in again

I'm trying learn Android Firebase. When I program a code of Register user, it work successfully. But when I called "userProfileChangeRequest" method
to change username OR profile picture uri it is work successfully, but new data isn't view to user before he log out and sign in again.
Why? What is the problem?
Here is my code:
private void getUriPicture() {
if(uriImage == null){
//user didn't select profile picture
return;
}
else if(!App.isOnline(this)) {
Toast.makeText(this, getResources().getString(R.string.checkInternetConnection), Toast.LENGTH_SHORT).show();
return;
}else{
mStorage = FirebaseStorage.getInstance().getReference();
//upload picture to get Path
Log.e(TAG,"test3");
StorageReference path = mStorage.child("ProfilePicture").child(uriImage.getLastPathSegment()
+ "_"
+ App.randomNumber()
+ "_"
+ App.randomNumber());
Log.e(TAG,"test4"+path);
path.putFile(uriImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Log.e(TAG,"Upload success");
#SuppressWarnings("VisibleForTests") Uri downloadUrl= taskSnapshot.getDownloadUrl();
//Preview profile picture before set it to user
Picasso.with(Setting.this).load(downloadUrl).into(profilePicture);
setUserProfilePicture(downloadUrl);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
TF=false;
Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
private void setUserProfilePicture(Uri downloadUrl) {
//mProgress.setMessage(getResources().getString(R.string.updateProfile));
FirebaseUser user = mAuth.getCurrentUser();
if(user != null) {
Log.e(TAG,"test6");
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUrl)
.build();
user.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.e(TAG, "Update Profile Successful");
Toast.makeText(Setting.this, getResources().getString(R.string.updateSuccessful), Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e(TAG, "Update Failure");
Toast.makeText(Setting.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Maybe you could try to update the user image in UI inside onCompleteListener ? As there are no view update actions done after you UserProfileChangeRequest.

Categories

Resources