Deleting CardView Data from UI and Firebase Realtime Database? - java

I have a RecyclerView with CardViews which come from my Firebase Realtime Database for different activities, for example, daily meals. I have added a delete button to the CardView which I would like to implement a delete from UI and database function. I know how to do these both separately, but I am unsure how to update the database after deleting the CardView from the UI.
At the moment, it is deleting from UI but not database, so when I go back to the activity, the card reappears. Each meal has its own random ID, not sure if that makes a difference but thought it is important to note.
Adapter Delete Function:
foodHolder.deleteMeal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
meals.remove(position);
notifyDataSetChanged();
}
});
Meal Activity (Where adapter is set):
mealRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
int total = 0;
for (DataSnapshot mealSnapshot : task.getResult().getChildren()) {
String grams = mealSnapshot.child("grams").getValue(String.class);
if (grams == null) {
textViewFoodCounter.setText("0");
} else {
total += Integer.parseInt(grams);
textViewFoodCounter.setText(String.valueOf(total));
}
if (meals != null) {
noMealsImg.setVisibility(View.GONE);
noMealsText.setVisibility(View.GONE);
} else {
noMealsImg.setVisibility(View.VISIBLE);
noMealsText.setVisibility(View.VISIBLE);
}
progressBar.setMax(1000); // make dynamic
ObjectAnimator.ofInt(progressBar, "progress", Integer.parseInt(grams))
.setDuration(300)
.start();
Meal data = mealSnapshot.getValue(Meal.class);
meals.add(data);
}
foodAdapter = new FoodAdapter(meals);
foodRecyclerView.setAdapter(foodAdapter);
} else {
Log.d("TAG", task.getException().getMessage());
}
}
});
CardView:
Firebase Meal Hierarchy:

You can do something like this. If anything is updated in the firebase database you can load your new data using addValueEventListener and onDataChange.
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance().reference;
DatabaseReference dmoRef = firebaseDatabase.getReference().child(serialId);
dmoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//get your updated data
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(), "Error fetching data", Toast.LENGTH_LONG).show();
}
});

Related

Get a specific nested child and count it

I making an Attendance App.
In the app there is a function to know how many event an users already attend and what event they attend.
What i want is something like this (i dont know if it work or there is a better way):
private void fetchSpecificEvent() {
//Fetch event that user already attend
FirebaseRecyclerOptions<ModelEvent> options = new FirebaseRecyclerOptions.Builder<ModelEvent>()
.setQuery(referenceForSpecificEvent, snapshot -> new ModelEvent(
Objects.requireNonNull(snapshot.child("eventID").getValue()).toString(),
...
...
...
)
.build();
...
}
private void getAttendanceCount(){
//Get how many event user already attend
referenceForCount.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
attendanceCount = (int) snapshot.getChildrenCount();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
The main problem is i dont know what reference i use on: referenceForSpecificEvent and referenceForCount
This the JSON:
This the full JSON : https://pastebin.com/k65jhMUC
Sorry for the title, i dont know the keyword for it.
I found the way to do it. Probably not the best (because i cant really explain what i want) but it works.
reference = FirebaseDatabase.getInstance().getReference().child("Attendance");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
for (DataSnapshot eventSnapshot: dataSnapshot.getChildren()) {
//Get Event ID
Log.i(TAG, eventSnapshot.getKey());
for (DataSnapshot userSnapshot: dataSnapshot.child(Objects.requireNonNull(eventSnapshot.getKey())).getChildren()) {
//Get User ID
//Log.i(TAG, userSnapshot.getKey());
if(Objects.equals(userSnapshot.getKey(), stringEmail)){
intCount++;
listEvent.add(eventSnapshot.getKey());
}
}
}
}
else{
Log.i(TAG, "No Value Found");
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d(TAG, error.getMessage()); //Don't ignore errors!
}
});

addsnapshotlistener triggers even though there is no update in Firebase

In my app, the homepage activity holds a sectioned recyclerview, in which the value is initiated by querying Firebase. The data retrieval and the recyclerview was working well at first.
Then, I tried to implement addsnapshotlistener to automatically update my activity without needing the user to refresh the page independently.
However, when I run my code, the recyclerview repeated the same sectioned recyclerview twice.
Here is the code for my activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.homepage);
mAuth = FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
///storageRef = FirebaseStorage.getInstance().getReference();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
MainRecyclerView = findViewById(R.id.MainContainer);
SignoutButton = findViewById(R.id.SignOutbutton);
checkUserType();
SignoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FirebaseAuth.getInstance().signOut();
///mAuth.GoogleSignInApi.signOut(apiClient);
Intent i = new Intent(HomePage.this, Login.class);
startActivity(i);
}
});
///queries data from firebase
initData();
BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
bottomNavigationView.setSelectedItemId(R.id.appointment);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()){
case R.id.search:
startActivity(new Intent(getApplicationContext(),Search.class));
overridePendingTransition(0,0);
return true;
case R.id.appointment:
return true;
case R.id.profile:
startActivity(new Intent(getApplicationContext(),Profile.class));
overridePendingTransition(0,0);
return true;
}
return false;
}
});
UpdateToken();
}
#Override
protected void onStart() {
super.onStart();
sectionList.clear();
apnmntList.clear();
CollectionReference colref = db.collection("appointmentsColl").document(UserId)
.collection("Date");
///check for updates inside of the collections
HPListener= colref.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
for (QueryDocumentSnapshot document : value) {
///query all the values again
db.collection("appointmentsColl").document(UserId)
.collection("Date").document(document.getId())
.collection("appointmentsID")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
apnmntList = new ArrayList();
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(
querysnapshot.getString("customer name"),
querysnapshot.getString("barberID"),
querysnapshot.getString("shop name"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
apnmntList.add(details);
section = new Section(document.getString("date"),apnmntList);
}
///notify recyclerview
sectionList.add(section);
mainRecyclerAdapter.notifyDataSetChanged();
}
});
}
}
});
}
#Override
protected void onStop() {
super.onStop();
HPListener.remove();
}
private void checkUserType() {
DocumentReference docRef = db.collection("Users").document(UserId);
docRef.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value, #Nullable FirebaseFirestoreException error) {
if (value.exists()) {
userType = "Users";
} else {
userType = "Barbers";
}
}
});
}
private void initData(){
db.collection("appointmentsColl").document(UserId)
.collection("Date")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
///getting the list of appointments and their details
db.collection("appointmentsColl").document(UserId)
.collection("Date").document(document.getId())
.collection("appointmentsID")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
#Override
public void onComplete(#NonNull Task<QuerySnapshot> task) {
apnmntList = new ArrayList();
for (DocumentSnapshot querysnapshot: task.getResult()){
apnmtDetails details = new apnmtDetails(
querysnapshot.getString("customer name"),
querysnapshot.getString("barberID"),
querysnapshot.getString("shop name"),
querysnapshot.getString("name"),
querysnapshot.getString("type"),
querysnapshot.getString("status"),
querysnapshot.getString("price"),
querysnapshot.getString("time slot"));
///adding appointmnets into an arraylist
apnmntList.add(details);
///saving the value of the section title and the appointments arraylist inside one object
section = new Section(document.getString("date"),apnmntList);
}
////initializing a new array list with the section's objects
sectionList.add(section);
///initializes the main recyclerview
LinearLayoutManager manager = new LinearLayoutManager(HomePage.this);
manager.setReverseLayout(true);
manager.setStackFromEnd(true);
MainRecyclerView.setLayoutManager(manager);
MainRecyclerView.setAdapter(mainRecyclerAdapter);
}
});
}
}else{
Toast.makeText(HomePage.this,"failed",Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.i("Check", e.toString() );
}
});
}
private void UpdateToken() {
FirebaseUser firebaseUser= FirebaseAuth.getInstance().getCurrentUser();
String refreshToken= FirebaseInstanceId.getInstance().getToken();
Token token= new Token(refreshToken);
FirebaseDatabase.getInstance().getReference("Tokens").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(token);
}
Here is what my output looks like before and after implementing addsnapshotlistener:
Before
After
I tinkered with the addsnapshotlistener for a while because I was not sure whether it is the cause for the problem, so I tried to replace the method inside the addsnapshotlistener with:
finish();
startActivity(getIntent()
I thought this would work, but when I tried to run my code, the homepage started to refresh itself endlessly without stopping.
I tried to search for people with the same problem as my own, but the posts that I find stated that their addsnapshotlistener triggers correctly but return twice the instance of the data.
The method triggers itself when I open my activity, and it triggers itself even if there are no updates in Firebase.
I would appreciate it if anyone can help me with this problem or maybe guide me to any link or post that can help solve my problem.
You mention that your data retrieval was working well at first. Have you changed anything recently?
From reading your code, I cannot see where you are handling any errors you might encounter. A listener may fail due to a security setting change or an invalid query.
It would help if you implemented an error callback to help you better understand what has happened. For example, you can capture the error message as e and output the error.
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
Documentation:
db.collection("cities")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot snapshots,
#Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
if (dc.getType() == Type.ADDED) {
System.out.println("New city: " + dc.getDocument().getData());
}
}
}
});

Check if a value exist in more then on child Firebase Database in Android

I'm developing an android application for college project using Java and Firebase. I want to store the details of faculties working in college like name,email,department etc based on their position. I have created 3 child nodes HOD,Class mentor and lecturers inside Faculties as you can see that in here.
my problem is when I want to add the members inside any one these child I want to check if that members email ID is exist in any other childs. For example I want to add a member in HOD child.If this members email existed inside Lecturers child it should display Toast user already existed as Lecturer else it should add member inside Lecturer.
I used this code.
post = "HOD";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
post = "Class mentor";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
post = "Lecturer";
databaseReference.child(post).orderByChild("email").equalTo(email).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
Toast.makeText(MainActivityAddFaculty.this, "User already exist in "+post, Toast.LENGTH_SHORT).show();
} else {
checkData();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivityAddFaculty.this, databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
});
It works fine but it's lengthy and also it takes time to check.If there is any better solution that would be very helpful.
This is is my code complete code for adding Faculties.
public class MainActivityAddFaculty extends AppCompatActivity {
private TextInputLayout addName, addEmail;
private TextInputEditText addEditName, addEditEmail;
private Button addBtn;
private Spinner addPositionSpinner,addDeptSpinner,addYearSpinner;
private TextView addPosition,addDept,addYear;
private String sDept = "Select department",sPost = "Select position",sYear = "Select year";
private String position,department,year,post;
private boolean b = false;
private FirebaseDatabase firebaseDatabase;
private FirebaseStorage firebaseStorage;
private DatabaseReference databaseReference,databaseReference2;
private StorageReference storageReference;
LoadingDialog loadingDialog;
private String facultyID;
private String name,email;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_faculty);
setTitle("Add Hod");
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
addName = findViewById(R.id.addFName);
addEmail = findViewById(R.id.addFEmail);
addEditName = findViewById(R.id.addFEditName);
addEditEmail = findViewById(R.id.addFEditEmail);
addBtn = findViewById(R.id.addFBtn);
addPositionSpinner = findViewById(R.id.addFPositionSpinner);
addPosition = findViewById(R.id.addFPosition);
addDeptSpinner = findViewById(R.id.addFDepartmentSpinner);
addDept = findViewById(R.id.addFDepartment);
addYearSpinner = findViewById(R.id.addFYearSpinner);
addYear = findViewById(R.id.addFYear);
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("FACULTIES");
facultyID = databaseReference.push().getKey();
loadingDialog = new LoadingDialog(MainActivityAddFaculty.this);
//selectPosition();
//TODO:Select position
List<String> categories = new ArrayList<>();
categories.add(0,"Select position");
categories.add("HOD");
categories.add("Class mentor");
categories.add("Lecturer");
ArrayAdapter<String> dataAdapter;
dataAdapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addPositionSpinner.setAdapter(dataAdapter);
addPositionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
addPosition.setText(parent.getSelectedItem().toString());
test();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivityAddFaculty.this, "Select a position", Toast.LENGTH_SHORT).show();
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name = addEditName.getText().toString().trim();
email = addEditEmail.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(MainActivityAddFaculty.this, "Enter name", Toast.LENGTH_SHORT).show();
}else {
if (TextUtils.isEmpty(email)) {
Toast.makeText(MainActivityAddFaculty.this, "Enter email.", Toast.LENGTH_SHORT).show();
} else {
checkData();
}
}
}
});
}
private void test(){
position = addPositionSpinner.getSelectedItem().toString();
if (position.equals(sPost)){
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
}else if (position.equals("HOD")){
addDeptSpinner.setVisibility(View.VISIBLE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.VISIBLE);
addYear.setVisibility(View.GONE);
} else if (position.equals("Class mentor")){
addDeptSpinner.setVisibility(View.VISIBLE);
addDept.setVisibility(View.VISIBLE);
addYearSpinner.setVisibility(View.VISIBLE);
addYear.setVisibility(View.VISIBLE);
} else if (position.equals("Lecturer")){
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
} else {
addDeptSpinner.setVisibility(View.GONE);
addYearSpinner.setVisibility(View.GONE);
addDept.setVisibility(View.GONE);
addYear.setVisibility(View.GONE);
}
}
private void checkData(){
position = addPositionSpinner.getSelectedItem().toString();
department = addDeptSpinner.getSelectedItem().toString();
year = addYearSpinner.getSelectedItem().toString();
if (position.equals(sPost)){
Toast.makeText(this, "Select position", Toast.LENGTH_SHORT).show();
} else if (position.equals("HOD")){
if (department.equals(sDept)){
Toast.makeText(MainActivityAddFaculty.this, "Select department.", Toast.LENGTH_SHORT).show();
} else {
AddHOD addHOD = new AddHOD(name,position,department,email,facultyID);
databaseReference.child(position).child(facultyID).setValue(addHOD).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
}else if (position.equals("Class mentor")){
//add Class mentor process started
if (!department.equals(sDept)){
if (!year.equals(sYear)) {
AddClassMentor addClassMentor = new AddClassMentor(name, position, department, year, email, facultyID);
databaseReference.child(position).child(facultyID).setValue(addClassMentor).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}else {
Toast.makeText(this, "Select year.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Select department", Toast.LENGTH_SHORT).show();
}
} else if (position.equals("Lecturer")){
AddLecturer addLecturer = new AddLecturer(name,position,email,facultyID);
databaseReference.child(position).child(facultyID).setValue(addLecturer).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivityAddFaculty.this, "Faculty added successfully", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivityAddFaculty.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
} else {
Toast.makeText(this, "Entry is pending.", Toast.LENGTH_SHORT).show();
}
}
}
Firebase's queries work on a list of nodes. Since you have a hierarchy, you'll need to fire the same query for each list you have in there, as you're doing today.
As usual when dealing with NoSQL databases, the solution is to model the data in a way that makes the use-case easiest. If you want to search across all members, store a single list of members:
"members": {
"$memberid": {
"email": "membersemail#institute.edu",
"memberType": "Class mentor" // or "HOD" or "Lecturer"
}
}
With the above structure you only have to execute one query to find all members with a specific email address.
You can either use the above structure to replace the three structures you currently have, or you can use it as an additional structure just for this use-case. Which one to choose depends on the other use-cases in your app, there is no solution that is right for all apps, just the one that works for you.
Enforcing uniques across values as you're doing here, will lead to scalability issues over time, as you:
Need to search across all members, which takes more time as you get more members.
More importantly: you will need to use a transaction to insert new users, to reduce the chances that multiple users claim the same email address at the same time.
This leads to a second scaling problem, as you'll need to run that transaction on the evert-growing /members node.
Finally: a malicious user can bypass the transaction by writing their own code, and still claim any email address.
Ensuring uniqueness on Firebase is only really enforceable if you use those values as the key in a list, so by maintaining a (additional) list of email addresses.
For more on this see:
Firebase security rules to check unique value of a child #AskFirebase
Firebase android : make username unique
How do you prevent duplicate user properties in Firebase?
Firebase realtime database validation username and email

Firebase reading data from multiple references

I am trying to fetch data from Firebase database from multiple child in single function. I have two child nodes in Firebase Favorites and Users
I am using RecyclerView to show list of Favorites User but i want to fetch one value name "Online" from Users node.
I add addValueEventListener on Favorites and add addListenerForSingleValueEvent on Users within Favorites addValueEventListener, but my addListenerForSingleValueEvent give null value.
There is my code:
mFavouriteDBRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mList.clear();
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot snap: dataSnapshot.getChildren()){
final Favourites user = snap.getValue(Favourites.class);
final FavouritesList[] holdObj = null;
//if not current user, as we do not want to show ourselves then chat with ourselves lol
try {
if(mAuth.getCurrentUser().getUid().equals(user.getUserId())){
//Firebase Reading data
mUsersDBRef = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).child("online").onDisconnect().setValue(false);
String local =dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("online").getValue().toString();
if(local.equals("true")){
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "true","Link");
}else{
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "false","Link");
}
mList.add(holdObj[0]);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
populaterecyclerView();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here my populaterecyclerView(); Class
private void populaterecyclerView(){
adapter = new UserFavouritesMeHomeListAdapter(context,mList);
adapter.setClickListener(UserFavouritesMeListHomeFragment.this);
recyclerView.setAdapter(adapter);
}
Thanks
Link of Image:
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124042847_file_cover.jpg
Data want to fetch from while reading Favorite
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124044659_file_cover.jpg

Firebase Delete Child onButtonClick

My problem is I cant delete a single child from the firebase database, either nothing happens or it deletes the whole child and all data. I've looked around and tried multiple solutions but for whatever reason mine wont work and I out of ideas why.
Any help is appreciated.
Java class.
//get data passed from viewpasswords and put them into textviews
name.setText(getIntent().getExtras().getString("data"));
password.setText(getIntent().getExtras().getString("pass"));
//get current user id and reference to database
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userID = user.getUid();
dbRef = FirebaseDatabase.getInstance().getReference();
//button onclick stuff
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DeleteData();
}
});
exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(DecryptPassword.this, ViewPasswords.class);
startActivity(intent);
}
});
}
private void DeleteData() {
final String passName = name.getText().toString();
Query query = dbRef.child("Passwords").child(userID).orderByChild("PasswordName").equalTo(passName);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot itemSnapshot : dataSnapshot.getChildren()){
dataSnapshot.getRef().removeValue();
Toast.makeText(DecryptPassword.this, "Success", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(DecryptPassword.this, ViewPasswords.class);
startActivity(intent);
}
}else{
Toast.makeText(DecryptPassword.this, "Failed to delete", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(DecryptPassword.this, "Error occurred sorry", Toast.LENGTH_SHORT).show();
}
});
}
Firebase Database:
Thanks.
dataSnapshot.getRef().removeValue();
Change this part to:
itemSnapshot.removeValue();

Categories