I want to change the value of child "toggleStatus" under Reference "BetSlip" as shown below. The already set value is "on" so I want such that when I click the button the value of "toggleStatus" is changed to "off"
BetSlipActivity.toggleCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = betSlip.get(position).getTimeStamp();
String toggleStatus = betSlip.get(position).getToggleStatus();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
//set value to off
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
//set value to on
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
If you've got the DataSnapshot for a path in the database, it's easy to get the DatabaseReference that you need to update it:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
ds.child("toggleStatus").getRef().setValue("off");
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
ds.child("toggleStatus").getRef().setValue("on");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
Since you're updating the node based on its existing value, strictly speaking you might need to use a transaction for it.
Related
I am trying to query my Messages table for three things. The first is any messages with that involve the current user logged in. Then, I want to get the user id of the person the current user has a coversation with. And finally, I want to check if any of the messages were seen. But right now my query only runs the first and last queries and not the second one. But I don't know why.
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot snapshot1 : snapshot.getChildren()) {
String messageToID = snapshot1.getKey();
DatabaseReference messageRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query = messageRef.orderByChild("to").equalTo(firebaseUser.getUid());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
if (dataSnapshot.exists()) {
DatabaseReference messageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid()).child(messageToID);
Query query2 = messageKeyRef.orderByChild("isSeen").equalTo(false);
query2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataShot) {
if (dataShot.exists() && count > 0) {
//Log.d("TAG2", "count if: " + count2);
messages_text.setText("" + Math.toIntExact(count));
messages_text.setVisibility(View.VISIBLE);
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
messages_text.setVisibility(View.GONE);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
//Log.d("TAG1", "User to: " + messageToID);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Your first addValueEventListener already loads all data for the current user, so there is no need to go back to the database to load that data again. Instead you should check the properties of each message in your application code with something like:
DatabaseReference userMessageKeyRef = dbRef.child("Messages").child(firebaseUser.getUid());
userMessageKeyRef.addValueEventListener(new ValueEventListener() {
for (DataSnapshot parentSnapshot : snapshot.getChildren()) {
for (DataSnapshot messageSnapshot : addValueEventListener.getChildren()) {
String messageToID = messageSnapshot.getKey();
String toValue = messageSnapshot.child("to").getValue(String.class);
Boolean isSeenValue = messageSnapshot.child("isSeen").getValue(Boolean.class);
if (toValue.equals(firebaseUser.getUid()) && isSeenValue == true) {
...
}
}
}
});
I am trying to select data from my database and I want to check if a specific child node has a one or a zero as it's value. If it has a 1 then I don't want to show info from that specific user. If it has a zero then I want to show info from that specific user.
I did it in a method above the one I'm working on(I followed this answer How to get child of child value from firebase in android?) and I got it working no problem. But I can't do the same for my other method and I have been trying all day now.
As of right now, the only result I am getting is the list not showing up at all. Can someone please help me ?
Method that works:
private void getPosts() {
followingList = new ArrayList<>();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Video_Posts");
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
myPosts.clear();
//followingList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Post post = snapshot.getValue(Post.class);
if (followingList.isEmpty()) {
if (!post.getPublisher().equals(firebaseUser.getUid())) {
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(post.getPublisher());
DatabaseReference zone1NameRef = zone1Ref.child("acc_closed");
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Log.i(TAG, dataSnapshot.getValue(String.class));
if (dataSnapshot.getValue(String.class).equals("1")) {
//Toast.makeText(getContext(), "Account closed", Toast.LENGTH_SHORT).show();
} else if (dataSnapshot.getValue(String.class).equals("0")) {
//Toast.makeText(getContext(), "Not closed.", Toast.LENGTH_SHORT).show();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef
.child("Follow")
.child(firebaseUser.getUid())
.child("following")
.child(post.getPublisher());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do something
Toast.makeText(getContext(), "Following.", Toast.LENGTH_SHORT).show();
} else {
//Do something else
myPosts.add(post);
Collections.shuffle(myPosts);
//Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//Log.w(TAG, "onCancelled", databaseError.toException());
}
});
} else if (myPosts == null) {
Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getContext(), "List is not empty.", Toast.LENGTH_SHORT).show();
for (String id : followingList) {
assert post != null;
if (!post.getPublisher().equals(id)) {
myPosts.add(post);
Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();
} else if (myPosts == null) {
Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
}
}
}
}
adapterExplorer.notifyDataSetChanged();
progressBar.setVisibility(View.GONE);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Method that doesn't work:
private void searchUsers(String s) {
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(user.getId());
DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());
//mUsers.add(user);
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapS) {
if (snapS.getKey().equals("1")) {
} else if (snapS.getKey().equals("0")){
//if (!snapS.exists()) {
Log.d("TAG", snapS.toString());
mUsers.add(user);
//}
}
//}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
Database:
"Users": {
"4mFQt8Lf3CTNrQF74sy8wwyFoLh1": {
"acc_closed": "0",
"bio": "",
"dateAdded": "19-06-2022 17:28:56",
"date_time": 1655674136805,
"device_token": "feGjHNzaR7S8yaV2HKg0rt:APA91bEXAiYwT52niHVxR2ENrcaKXSNs11Z5ss-g2gsDwTs4wbjqjcrN4ZUmemqiMzp6SZM6UXD5TFrc1JND_DoEgd-Ni9wMeCa73EzvKBAaj5aXJf1GjgjSsTVwBg1A6VvhvVwF1VSX",
"fullname": "Brandon",
"id": "4mFQt8Lf3CTNrQF74sy8wwyFoLh1",
"imageurl": "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/default.jpg?alt=media&token=befece91-9248-45ee-ab6f-b1b3d217c6b4",
"username": "bran1",
"verified": "false"
},
EDIT:
The code above (searchUsers) kind of works. When I put text into the search bar nothing shows up. But when I hit the back button and remove the keyboard the data shows up. It's like I'm actually waiting for data to change.
The simple fix is that you should call notifyDataSetChanged after you modified the data that the adapter shows, where right now you're calling it before that.
So move the call to userAdapter.notifyDataSetChanged() to right after mUsers.add(user):
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
DatabaseReference zone1Ref = zonesRef.child(user.getId());
DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());
zone1NameRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapS) {
if (snapS.getKey().equals("1")) {
} else if (snapS.getKey().equals("0")){
Log.d("TAG", snapS.toString());
mUsers.add(user);
userAdapter.notifyDataSetChanged(); // š
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.d("Error name", error.getMessage());
}
});
}
}
There is some more (but not related to the problem) room for optimization here, as the dataSnapshot you get in the outermost listener already contains the data for *alldata under/Users`.
So there's no need to add an other listener to get the acc_closed value for each user. Instead you can just navigate the initial snapshot like this:
Query query = FirebaseDatabase.getInstance().getReference("Users");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
DataSnapshot snapS = userSnapshot.child("acc_closed");
String accClose = snapS.getValue(String.class)
if (accClose.equals("0")){
Log.d("TAG", accClose);
mUsers.add(userSnapshot.getValue(User.class));
userAdapter.notifyDataSetChanged();
}
}
}
Finally: your code retrieves all /Users to then only use the users who have acc_close being equal to "0". This wastes (your and your user's) bandwidth, especially as you're adding more users. It's much better to use a query to retrieve only the necessary data from the server/database:
DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query query = usersRef.orderByChild("acc_closed").equalTo("0");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (search_bar.getText().toString().equals("")) {
recyclerView.setVisibility(View.INVISIBLE);
}
mUsers.clear();
for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
mUsers.add(userSnapshot.getValue(User.class));
}
userAdapter.notifyDataSetChanged();
}
Hy, I'm writing an application that has to get specific data from firebase using the position of the item in the listView. My problem is that I have no idea how to take it this item on firebase.
For all child of Torneo I have to control all the nameCreator.
I have tried this:
public Boolean RegisterUser(Data data, final int position, final Context c){
boolean registration;
final ArrayList<String> Creator = new ArrayList<>();
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(data.child("nameCreator").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
return registration;
}
Data is a class with some getter and setter that I have created.
position is the position of the element on the list view.
Thanks for answers.
Change the following:
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
into this:
databaseReference.child("Tornei").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(datas.child("nameCreator").getValue().toString());
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Then you will be able to loop and retrieve the value of nameCreator
It's easy.
ćStep 1 | Get Snapshot Data and Save in Global Variableć
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference fruitsReference = rootReference.child("fruits");
DataSnapshot fruitsData;
#Override
protected void onStart() {
super.onStart();
fruitsReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshots) {
fruitsData = dataSnapshots;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
ćStep 2 | Find Your Target Position through the Loopć
public void onClick(View view) {
int index = 0;
for (DataSnapshot childSnapshot : fruitsData.getChildren()) {
if (index == 1) { //your target position
DatabaseReference currentFruitReference = childSnapshot.getRef();
currentFruitReference.setValue("peach"); //do whatever you want
}
index++;
}
}
I want to get to a listview the data on "Categorias" folder, but i try everthing and i can't do this.
Fragment code:
myRef.addValueEventListener(new ValueEventListener() {
public static final String TAG = "TNW";
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
list3 values = td.values();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity().getApplicationContext(), "Ese usuario ya existe ", Toast.LENGTH_SHORT).show();
}
});
Its very simple, here is the code to fetch your values.
DatabaseReference db = FirebaseDatabase.getInstance().getReference("people");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
//get the categorias node
DataSnapshot dsCategorias = ds.child("categorias");
//loop inside the categorias node for all children
for(DataSnapshot dbValSnapshot: dsCategorias.getChildren()){
//Assuming all children have only boolean values
//getting the key and the values
String key = dbValSnapshot.getKey();
boolean value = dbValSnapshot.getValue(Boolean.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Let me know if you are not able to understand any part of my code. Thanks
Using Firebase, I'm trying to display to the user people they have matched with. I already have valid data for testing this and I have already run tests with sample data to see if everything else works.
Now, when I use real data from Firebase, problems occur.
This is what I have for code:
public String username = "";
public String profileImage = "";
public String discussion = "";
private void FetchMatchInformation(final String key, final String choice) {
DatabaseReference matchDb = FirebaseDatabase.getInstance().getReference().child("answers").child(key);
matchDb.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String opposite = postSnapshot.getValue(String.class);
if(opposite.equals("agree") && choice.equals("disagree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
} else if(opposite.equals("disagree") && choice.equals("agree")) {
DatabaseReference found = FirebaseDatabase.getInstance().getReference().child("users").child(postSnapshot.getKey());
found.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals("username")) {
username = postSnapshot.getValue(String.class);
}
if(postSnapshot.getKey().equals("providerId")) {
String provider = postSnapshot.getValue(String.class);
if(provider.equals("google.com")) {
Uri photoUrl = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl();
String originalPieceOfUrl = "s96-c/photo.jpg";
String newPieceOfUrlToAdd = "s400-c/photo.jpg";
String photoPath = photoUrl.toString();
String newString = photoPath.replace(originalPieceOfUrl, newPieceOfUrlToAdd);
profileImage = newString;
} else if(provider.equals("facebook.com")) {
profileImage = FirebaseAuth.getInstance().getCurrentUser().getPhotoUrl().toString() + "?type=large";
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
FirebaseDatabase.getInstance().getReference().child("debates").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
if(postSnapshot.getKey().equals(key)) {
discussion = postSnapshot.getValue(String.class);
break;
}
break;
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
MessagesObject objDisc = new MessagesObject(username, discussion, profileImage);
resultsMessages.add(objDisc);
mMessagesAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
So what's happening is I'm getting the user's username, their profile image, and figuring out the value, which I called discussion after determining the valid key. These values are all being accessed from different tree structures from the same real-time database.
Now, at the end of the if or else-if statement, I create and instantiate the MessagesObject by passing in the username, profile image, and discussion variables. I then add this object to the List<MessagesObject> called resultMessages. I then notify my custom adapter mMessagesAdapter that the data has changed.
Like I said, all the other pieces of code work perfectly fine. It's just when I pass username, discussion, and profileImage it always passes an empty string. I know this from using the debugger.
Why is that? It should not be doing that.