Reputation: 47
My idea is to allow a user add things in his userlist. When user clicks checkbox, it creates an item with data in FireBase database (I want to sort the user list in the future by the time).
I do so by the following code:
favCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
//Add item
favMap.put("comicsId", comicsId);
favMap.put("comicsGenreId", comicsGenreId);
favMap.put("comicsTitle", comicsTitle);
favMap.put("time", ServerValue.TIMESTAMP);
favListRef.setValue(favMap);
}
if(!b){
//Remove item
favListRef.removeValue();
}
}
});
And to make checkBox be checked (if user has already added item before) I use the code:
//Check if already added
favListRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
if(dataSnapshot1.getValue() != null && !dataSnapshot1.getValue().equals("")){
//Item already added set as checked
favCheckBox.setChecked(true);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
So everything is fine except for every time when the "checker" code finds out that an item has already added it sets the checkbox as checked and then time in database updates (that ruins my idea of sorting by time).
How can I implement the "TIMESTEAMP" idea with FireBase database and not update time after every check?
Would like to see your answers and pieces of advice. Thanks in advance.
Upvotes: 0
Views: 90
Reputation: 47
Thanks to Andy.
To handle the issue I made items adding and removing by onClickListener :
boolean checkBoxChecked;
...
//ClickListener
favCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(checkBoxChecked){
//Remove item
favListRef.removeValue();
checkBoxChecked = !favCheckBox.isChecked();//false
}
if(!checkBoxChecked){
//Add item
favMap.put("comicsId", comicsId);
favMap.put("comicsGenreId", comicsGenreId);
favMap.put("comicsTitle", comicsTitle);
favMap.put("time", ServerValue.TIMESTAMP);
favListRef.setValue(favMap);
checkBoxChecked = favCheckBox.isChecked();//true
}
}
});
//Check if user already added item
favListRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()){
if(dataSnapshot1.getValue() != null && !dataSnapshot1.getValue().equals("")){
//Item was added
favCheckBox.setChecked(true);
checkBoxChecked = favCheckBox.isChecked();//true
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) { }
});
TIMESTAMP changes only when user clicks on checkBox.
Upvotes: 1