I have created a Like button in the App. When user click on the Like Button a Node called "Like Posts" with a child (random Key) is created where the details of the posts are saved as you can see in the Image.
But, when i click on the Like button again, the node should get removed as per standards. But, that's not happening.
This is my code :
holder.fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = likesReference.push().getKey();
FirebaseDatabase.getInstance().getReference("Users").child(firebaseAuth.getUid()).child("Liked Posts").child(id).removeValue();
Toast.makeText(context, "Removed from Favorites !", Toast.LENGTH_SHORT).show();
} else {
likesReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseAuth.getUid()).child("Liked Posts");
Toast.makeText(context, "Added to Bookmarks", Toast.LENGTH_SHORT).show();
likesReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HomeModel homeModel1 = new HomeModel(holder.newsTitleTextView.getText().toString().trim(), holder.newsDetailTextView.getText().toString().trim(),
holder.timesAgo.getText().toString().trim(), homeModel.getNewsImage(), homeModel.viewCounts);
String id = likesReference.push().getKey();
Log.e("KEY IS", id); //right one
likesReference.child(id).setValue(homeModel1);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
How to delete the "Liked Posts" ?
Related
I am deleting user's data in realtime database. However, whenever I am trying to delete it, there's this one child that remains. I don't know why it won't delete it, even though I have tried using .removeValue().
Here's the image of my database
as you can see the image above ( orange-ish line ) that is the data of the user, and every time I want to delete that user, the "termsAgreement" child remains, and here's my code on removing the whole child.
holder.btndel_stud.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Delete Student Record");
alert.setMessage("Are you sure you want to delete");
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
final String uniqueKey = addingStudentsArrayList.get(position).getUniqueid();
Toast.makeText(context, uniqueKey, Toast.LENGTH_SHORT).show();
databaseReference.child(uniqueKey).removeValue();
Toast.makeText(context, "Student has been deleted, re-authenticate to delete the Registered Email", Toast.LENGTH_SHORT).show();
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Cancelled", Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
alert.show();
}
});
so basically the user have to agree on terms and condition first and this is my code whenever the user will agree on the terms and conditions.
checkBoxAgreement.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
AgreementBtn.setEnabled(isChecked);
AgreementBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth userAuth = FirebaseAuth.getInstance();
final String firebaseUser = userAuth.getCurrentUser().getUid();
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
databaseReference.child("termsAgreement").setValue("yes");
Toast.makeText(TermsAndConditionActivity.this, "You have agreed to Terms and Condition", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), WelcomeStudentActivity.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
}
});
I really don't know why the termsAgreement remains even tho I use .removeValue() to the unique id wherein the information was saved.
When a user logs in, you get them to agree to the terms agreement. When they click the "AgreementBtn", it writes "yes" to /Users/{USER_ID}/termsAgreement. However, when this "AgreementBtn" is clicked, it doesn't check if this user's data has been deleted first - it just writes the value anyway.
final DatabaseReference currentUserDataRef = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser);
currentUserDataRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()) {
// this user's data has been deleted/doesn't exist yet
// TODO: do something, like re-register user
} else {
currentUserDataRef.child("termsAgreement").setValue("yes")
.addOnCompleteListener(TermsAndConditionActivity.this, new OnCompleteListener<Void> {
#Override
public void onComplete(Task<Void> task) {
/* TODO: listen for success/failure events here */
if (task.isSuccessful()) {
Toast.makeText(TermsAndConditionActivity.this, "You have agreed to Terms and Condition", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(), WelcomeStudentActivity.class));
} else {
// TODO: Handle error in task.getException()
Toast.makeText(TermsAndConditionActivity.this, "Error when agreeing to terms: " + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// TODO: Handle this error, don't ignore it.
Toast.makeText(TermsAndConditionActivity.this, "Error when fetching user data: " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
So it appears there's nothing inherently wrong with your code, but one with the flow of events. If a user's account is deleted, you prompt them to login with that email, which when they do log in, it writes termsAgreement = "yes" to where their user data was deleted.
Note: Don't use databaseReference as a variable name. Use something meaningful such as usersRef (for /Users) or currentUserDataRef (for /Users/{USER_ID}) as appropriate.
So the problem is with your terms & conditions database ref:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseUser);
Which is different from when you are deleting the data:
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
They are not the same database ref.
That's why when you are trying to use removeValue() it's not deleting at the right location.
I want to get the key of what item I click but what happens in my code that when I click the one item it shows all the key instead of showing only the key on what I clicked
Here is my Firebase structure
and here is my code
public ViewHolderClass(#NonNull final View itemView) {
super(itemView);
subjectName=itemView.findViewById(R.id.subjectName);
day=itemView.findViewById(R.id.day);
time=itemView.findViewById(R.id.time);
delete = itemView.findViewById(R.id.deleteIcon);
subCounter = itemView.findViewById(R.id.subCounter);
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("rhein_subject");
subjectName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int pos = getAdapterPosition();
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
Toast.makeText(itemView.getContext(), "Pos: " + dataSnapshot1.getKey(), Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
I don't know either where to put the pos I've been through the google for 3 days but still it hasn't answered my problem.
I have inserted data and displaying it in List view as I am new to Firebase i dont know how to delete it.
My data format:
Code that i have tried to delete is:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
member.setName(list.get(position));
}
});
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String str = member.getName().substring(0,24);
if (str == "") {
Toast.makeText(Retreivedata.this, "plz select record to delete", Toast.LENGTH_LONG).show();
}else {
ref.child("Member").child(str).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
ref.child(str).removeValue();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Toast.makeText(Retreivedata.this,"Record is deleted",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getApplicationContext(),Retreivedata.class);
startActivity(intent);
}
}
Suggest me what to set onclick of delete button.!!
I would suggest using firebase recycler adapter or android recycler view to load your data, but for your case this is what you can do:
Not the best way, but lets say you want to delete an item on click, and assuming that all names are different:
I assumed that member.getName() is giving you the name of the clicked item:
btnDelete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//ref
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Member");
//Query
Query query = ref.orderByChild("name").equalTo(member.getName());
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
//remove
ds.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
query.addValueEventListener(listener);
}
});
Im using exists() method of the snapshot object in Firebase to check if user exists on pressing the SignUp(register) button. But as soon as I press the button, both the if and else conditions are executed(else first). What is going wrong?
final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users");
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
databaseReference.addValueEventListener(new ValueEventListener() {
public static final String TAG = "user_REG";
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child(mobileNumber.getText().toString()).exists()){
Log.d(TAG, "onDataChange: if fired");
} else {
Log.d(TAG, "onDataChange: else fired");
if(confirmPass.getText().toString().trim().equals(userPass.getText().toString().trim())){
userModel userModel = new userModel(fullName.getText().toString(), userPass.getText().toString());
databaseReference.child(mobileNumber.getText().toString()).setValue(userModel);
Toast.makeText(user_reg.this, "Successfully Signed Up", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(user_reg.this, "Your Passwords do not match", Toast.LENGTH_SHORT).show();
}
}
}
First time mobileNumber doesn't exist, So else part is executed and child node value is added and as data is added under same node, onDataChange will fire again and this time, if part will be executed.
To prevent the onDataChange to call twice, Use SingleEventListener instead of ValueEventListener Like this
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = (String) dataSnapshot.getValue();
// do your stuff here with value
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Firebase_database
Card_view_android
In my android app, the user creates events and details are sent to the firebase database. The event then is visible as a card view inside another activity.
I wish to make this as when the user clicks on +add me in that card, his details get added to that card. This part is ready, but I want his details to be pushed to the database as well. Can anyone help me?
FirebaseUser current_user = FirebaseAuth.getInstance().getCurrentUser();
String uid = current_user.getUid();
DatabaseReference eventRef = FirebaseDatabase.getInstance().getReference().child("Events").child("lists");
String key = eventRef.push().getKey();
final DatabaseReference groupRef = eventRef.child("").child(key);
userRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final String uName = dataSnapshot.child("member").getValue().toString();
addMe.setText(uName);
groupRef.child("members").setValue(uName).addOnCompleteListener(new OnCompleteListener < Void > () {
#Override
public void onComplete(#NonNull Task < Void > task) {
Toast.makeText(v.getContext(), "Success Adding you in Event", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(v.getContext(), "some error", Toast.LENGTH_LONG).show();
}
});
The above code just adds a member child below my firebase database. I wish to have it appended inside the key of the card view clicked.