I try to delete a node from my FirebaseDatabase with removeValue() but it doesn't work .The strange thing is that when i delete it inside Recyclerview the node deleted successfully .
I pass the ref from Recyclerview with onclick in a new Activity using the code below .
final DatabaseReference itemRef = getRef(position);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// itemRef.removeValue();
Intent intentshowall2one= new Intent(Showcase.this, ShowProduct.class);
intentshowall2one.putExtra("S2Skey", itemRef.toString());
Showcase.this.startActivity(intentshowall2one);
and on the other activity
key = myIntent.getStringExtra("S2Skey");
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl(key);
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Make sure you have given proper reference before you remove a value. then,
you can use Completion listener instead of OnSuccessListener, Completion listener gives accurate result.
Try this out in Your Button or any Listener :
mDatabase.child(key).removeValue();
Toast.makeText(getApplicationContext(),"The Post has been removed Successfully ",Toast.LENGTH_LONG).show();
Or use this
mDatabase.chlid(key).removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Instead of :
mDatabase.removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(getApplicationContext(), "deleted ", Toast.LENGTH_SHORT)
.show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT)
.show();
}
});
Hope it works for You
Thanks for your answers Lutaaya Huzaifah Idris and Vignesh Kumar.I found out that the error was because i was using Greek words inside my path.Everything worked fine upload download and query the ref with Greek words but when i passing the ref to the other activity the ref changed .That is also strange.
Related
I am using ML kit's on device translation API to translate a text.Although the translation is working perfectly fine but I am unable to display the translated text in my text view.I tried using setText method but nothing is being displayed in text view.Everything is being displayed in the logcat.
I am working in Android Studio
edit:
This shows the model being downloaded
TranslatorOptions options =
new TranslatorOptions.Builder()
.setSourceLanguage(TranslateLanguage.ENGLISH)
.setTargetLanguage(TranslateLanguage.BENGALI)
.build();
final Translator englishBengaliTranslator =
Translation.getClient(options);
//DOWNLOAD THE MODEL
DownloadConditions conditions = new DownloadConditions.Builder()
.requireWifi()
.build();
englishBengaliTranslator.downloadModelIfNeeded(conditions)
.addOnSuccessListener(
new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
}
//#Override
public void onSuccess(Void v) {
// Model downloaded successfully. Okay to start translating.
// (Set a flag, unhide the translation UI, etc.)
Toast.makeText(getApplicationContext(), "Model Downloaded.Translation will start ", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Model couldn’t be downloaded or other internal error.
// ...
Toast.makeText(getApplicationContext(), "Model could not be Downloaded. ", Toast.LENGTH_SHORT).show();
}
});
In this snippet of the code I have called the translate function (as the model is now downloaded)
englishBengaliTranslator.translate(stringResult)
.addOnSuccessListener(
new OnSuccessListener() {
#Override
public void onSuccess(Object o) {
}
//#Override
public void onSuccess(#NonNull String translatedText1) {
textViewTranslatedText.setText(translatedText1);
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Error.
// ...
Toast.makeText(getApplicationContext(), "Text could not be translated. ", Toast.LENGTH_LONG).show();
}
});
I have used the setText function but still the translated text gets displayed in logcat and not in the textview(The translation works completely fine).How do I display it in my textView instead of logcat?Any leads would be helpful!
here is the image of logcat where translated text is displayed:enter image description here
Try this code,
englishBengaliTranslator.downloadModelIfNeeded(conditions)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// Model downloaded successfully. Okay to start translating.
// (Set a flag, unhide the translation UI, etc.)
Toast.makeText(getApplicationContext(), "Model Downloaded.Translation will start ", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(
new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// Model couldn’t be downloaded or other internal error.
// ...
Toast.makeText(getApplicationContext(), "Model could not be Downloaded. ", Toast.LENGTH_SHORT).show();
}
});
The above code does nothing. I have just removed the unnecessary interface.
But the below code does something. I mean it specifies the return type.
englishBengaliTranslator.translate(stringResult)
.addOnSuccessListener(new OnSuccessListener<String>() {
#Override
public void onSuccess(String s) {
if(textViewTranslatedText!=null)
textViewTranslatedText.setText(translatedText1);
else
Log.d(TAG, "onSuccess: translation Done but text view null");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
//Handle onFailure
}
});
I want to get and delete all the documents in a subcollection called "journal" but it doesn't work and did not show any toast message or errors.
It would be very helpful if someone tells me what is wrong. Thank you a lot.
This is the code I use to get and delete all the documents in a subcollection:
final String userid = FirebaseAuth.getInstance.getCurrentUser().getUid();
FirebaseFirestore. getInstance().collection("main").document(userid).collection("journal").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (final QueryDocumentSnapshot document : task.getResult()) {
db.collection("main").document(userid).collection("journal").document(document.getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(SettingsActivity.this, "Deleted: " + document.getId(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, "error getting: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
});
Firestore structure :
collection(main) ---> document(userid)---> collection(journal)---> document 1
---> document 2
--> document 3
Try this.
final String userid = FirebaseAuth.getInstance().getCurrentUser().getUid();
FirebaseFirestore.getInstance().collection("main").document(userid).collection("journal").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
for (DocumentSnapshot document: queryDocumentSnapshots.getDocuments()) {
db.collection("main").document(userid).collection("journal").document(document.getId()).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(SettingsActivity.this, "Deleted: " + document.getId(), Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
});
Also, please make sure you have set your db rules to allow delete event
I have realtime database in firebase it look like this
Now I want to delete value by key in android (java).
I have tried this code
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("coating").child("88").removeValue().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(activity, "on success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(activity, "on success"+e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I get success response in onSuccess Method but value in database is not deleted.
As per this document
check out last para about delete and update ui
I'm currently making a method that allows current logged in user to sign up a new user and add them into as their downline friends using firebase. And while i was developing this method i realise that I've been bloating too much firebase functions into one method and i believe this would cause trouble when something is wrong with the inner function.
private void ValidateAccount(final String name, final String phone,final String email,
final String password, final String confirmPassword,
final String points,
final DatabaseReference RootRef, final FirebaseAuth firebaseAuth) {
firebaseAuth.createUserWithEmailAndPassword(email,password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
final FirebaseUser userkey = firebaseAuth.getCurrentUser();
final String userkeyString = userkey.getUid();
RootRef.child(userkeyString)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(!(dataSnapshot.exists())){
HashMap<String, Object> userDatamap = new HashMap<>();
final HashMap<String, Object> currentUserDatamap = new HashMap<>();
userDatamap.put("id",userkeyString);
userDatamap.put("phone",phone);
userDatamap.put("name",name);
userDatamap.put("email",email);
userDatamap.put("upline", upline);
addNewDownline(userkeyString);
currentUserDatamap.put("downlines", downlinesMaps);
RootRef.child(userkeyString).updateChildren(userDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
RootRef.child(currentUser.getId()).updateChildren(currentUserDatamap)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterDownlineActivity.this, "Congratulations your account has been created.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
firebaseAuth.signOut();
Intent intent = new Intent(RegisterDownlineActivity.this, HomeActivity.class);
startActivity(intent);
}
else{
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Network Error: Please try again.", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
else{
Toast.makeText(RegisterDownlineActivity.this,"The username already belong to someone else.",Toast.LENGTH_LONG).show();
loadingBar.dismiss();
Toast.makeText(RegisterDownlineActivity.this, "Please try again using another username.", Toast.LENGTH_LONG).show();
Intent intent = new Intent(RegisterDownlineActivity.this, MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(RegisterDownlineActivity.this, "System Error. Please try again later.", Toast.LENGTH_SHORT).show();
}
});
}
else{
Log.d( "FAIL", String.valueOf(task.getException()));
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed."+String.valueOf(task.getResult()),
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
try{
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
catch (RuntimeExecutionException task){
Toast.makeText(RegisterDownlineActivity.this, "Authentication failed: Email is already being used",
Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
For example, if something is wrong with the updateChildren() then the method will show failure at the updateChildren() part, but the createUserWithEmailAndPassword() will still execute.
What i wish to achieve is that whenever there's an error in the function all the function will not execute and shows the error.
If createUserWithEmailAndPassword() executed and updateChildren() failed, then inside .addOnFailureListener you can delete the user:
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
user.delete();
Toast.makeText(RegisterDownlineActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
I currently have a feature in my Android app that allows me to post a comment and attach a photo to it. The comment is uploaded to Cloud Firestore and the comment to Firebase Storage with a reference to the image through its download URL.
The problem I am having is that upon the first call to the method, it does not seem to retrieve the download URL, but when I make a second call it successfully retrieves it. Below I have included the method and this is simply called witin a button click listener.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_event_comments);
submitComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
newComment();
}
});
private void newComment() {
Date date = new Date();
EventComment mcomment = new EventComment();
mcomment.setComment(commentText.getText().toString());
mcomment.setDate_created(date);
// mcomment.setUsername(firebaseAuth.getCurrentUser().getEmail());
String commentID = Long.toHexString(Double.doubleToLongBits(Math.random()));
StorageReference filePath = firebaseStorage.child("Photos").child(imageUri.getLastPathSegment());
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(taskSnapshot.getDownloadUrl() != null){
imgDownloadUri = taskSnapshot.getDownloadUrl();
} else if(taskSnapshot.getMetadata().getDownloadUrl() != null) {
imgDownloadUri = taskSnapshot.getMetadata().getDownloadUrl();
}
Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
if (imgDownloadUri != null) {
mcomment.setImageUri(imgDownloadUri.toString());
}
firestore.collection("events").document(event_id).collection("comments").document(commentID)
.set(mcomment, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(EventCommentsActivity.this, "Comment posted successfully", Toast.LENGTH_SHORT).show();
}
});
}
firestore.collection("events").document(event_id).collection("comments").document(commentID)
.set(mcomment, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(EventCommentsActivity.this, "Comment posted successfully", Toast.LENGTH_SHORT).show();
}
});
I have debugged this multiple times and I am unsure as to what is causing this. Perhaps it's to do the way the callbacks work and by having it all in one method may cause problems?
Any feedback would be appreciated.
Cheers
I explain in code , see comment inside code , if you have any doubt then ask !
private void newComment() {
StorageReference filePath = firebaseStorage.child("Photos").child(imageUri.getLastPathSegment());
//start progessbar here
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if(taskSnapshot.getDownloadUrl() != null){
imgDownloadUri = taskSnapshot.getDownloadUrl();
} else if(taskSnapshot.getMetadata().getDownloadUrl() != null) {
imgDownloadUri = taskSnapshot.getMetadata().getDownloadUrl();
}
if (imgDownloadUri != null) {
//close progessbar here
mcomment.setImageUri(imgDownloadUri.toString());
}
Toast.makeText(getApplicationContext(), "Image uploaded", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
firestore.collection("events").document(event_id).collection("comments").document(commentID)
.set(mcomment, SetOptions.merge()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(EventCommentsActivity.this, "Comment posted successfully", Toast.LENGTH_SHORT).show();
}
});
}