1

Currently a have a floating action bottom in my detailView in this activity I bring the information of the Object with an intent. I want that when the user enters the detailView activity I have a filled heart if that Automoviles objectId already exist in the Favorites Node.if not add the information into the Database. If the favorite already exist and it has the filled heart if the user clicks again it will remove it from the database.

This is my favorites class:

public class Favorites {

private String id;
private  String automovilesId;
private  String userId;
private String fecha;

public Favorites() {
}

public Favorites(String automovilesId, String userId, String fecha) {
    this.automovilesId = automovilesId;
    this.userId = userId;
    this.fecha = fecha;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getAutomovilesId() {
    return automovilesId;
}

public void setAutomovilesId(String automovilesId) {
    this.automovilesId = automovilesId;
}

public String getUserId() {
    return userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getFecha() {
    return fecha;
}

public void setFecha(String fecha) {
    this.fecha = fecha;
}
}

At the moment i have this code:

        databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
    favoritesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
            final DatabaseReference usersRef = rootRef.child("Favorites");
            favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
            databaseReference.push().setValue(favorites);
        }
    });

Which Leads this entry in the database:

Firebase Data

This is all good but i need to verify also if favorites exist or not in the database or else everytime i run the android emulator it will create another favorites node.

Now i added more code . But when i run it and i add this AddFavorite method it will create infinite loops of Favorite Nodes in the database

    databaseReference = FirebaseDatabase.getInstance().getReference(AppModel.Favorites);
    favoritesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
            final DatabaseReference usersRef = rootRef.child("Favorites");
            favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
            databaseReference.push().setValue(favorites);


            usersRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    for(DataSnapshot ds : dataSnapshot.getChildren()) {
                        String car = ds.child("automovilesId").getValue(String.class);
                        Favorites fav =ds.getValue(Favorites.class);
                        String carId =fav.getAutomovilesId();
                        Log.i("No","Este es el nombre------>:"+carId);
                        String id=ds.getKey();
                        AddFavoritesuser();
                    }

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

        }
    });

This is the AddFavorite method and the delete method:

 private void AddFavoritesuser() {
    favoritesButton.setImageResource(R.drawable.ic_favorite);
    favorites = new Favorites(automoviles.getObjectId(), user.getUid(), AppModel.GetDate());
    databaseReference.push().setValue(favorites);
}

And the delete:

private void deleteFavoritesUser(String key) {
    favoritesButton.setImageResource(R.drawable.ic_favorite_border);
    databaseReference.child(key).getRef().removeValue();

}

In short i want it to verify if that object of Automoviles object exist . If it exist the user enters and sees the filled heart, if he wants to delete this favorite then he clicks again and it will run the deleteFavoritesUser method. But my question is what if Favorites is still no created in the database how can i also validate this?.

I runned the app again and I have the same vale created again:

As you can see I have the same automovilesId entry

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Felipe Franco
  • 171
  • 3
  • 15
  • it is happening because of **addValueEventListener**, It's keep calling whenever you add something in firebase collection. ideally you shouldn't need to insert from **onDataChange** method. – Krishna Sharma Oct 03 '18 at 19:20
  • Then how would i check if automovilesId already exists in the database? @KrishnaSharma – Felipe Franco Oct 03 '18 at 19:30
  • You already doing this outside the listener scope, so you just need to comment out this line of code **//AddFavoritesuser();** from onDataChange – Krishna Sharma Oct 03 '18 at 19:32
  • So how should i do all the other things i need to verify if it exists put the colored heart icon , and if the user clicks again it will erase that favoritesid from the database and put the border heart. @KrishnaSharma – Felipe Franco Oct 03 '18 at 19:38
  • basically you need to make your favorite button as a toggle button – Krishna Sharma Oct 03 '18 at 19:42

2 Answers2

0

basically you need to make your favorite button as a toggle button

favoritesButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // in place of YES/NO you can take any values to present true/false state
        boolean status = v.getTag() != null ? v.getTag().equals("YES") : false;
        v.setTag(status ? "NO" : "YES");
        if (status) {
            // Do favorite me
            //AddFavoritesuser();
        } else {
            // Do un favorite me
            //deleteFavoritesUser(key);
        }
    }
}
Krishna Sharma
  • 2,828
  • 1
  • 12
  • 23
0

everytime i run the android emulator it will create another favorites node.

This is happening because everytime you are trying to add a new object of Favorites class to the database, you are using the push() method, which generates a new random key everytime is called. This is what this method does. So in order to check a property from the database, you need to use in your reference the same key, not to generate another one. Please see in my answer from this post, where I have explained how you can achieve this.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193