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();
}
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'm using Firebase realtime database. Below is the structure
Problem Statement: Over a list of "Users", I need to delete child who's having coins = 0
So far I'm stuck here
DatabaseReference deleteRef = dbref.child("Users").child("coins");
Query deleteQuery = deleteRef.orderByValue().equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Any help will be appreciated :)
You need to order the list by the child coins like here:
DatabaseReference deleteRef = dbref.child("Users");
Query deleteQuery = deleteRef.orderByChild("coins").equalTo("0");
deleteQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
child.getRef().setValue(null);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
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.
Am kind of new to android and firebase but I need to get some values from my firebase realtime database similar to a select stmt in sql(select address,name from All_machines where terminal_id = "terminal_id").
When i did the code below i was getting a null pointer exeception. But I guess am yet to understand the concept.
mDatabase = FirebaseDatabase.getInstance().getReference("All Machines");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
if (childDataSnapshot.getValue() != null){
try {
if (childDataSnapshot.child("terminal_id").getValue().toString().equals(newTerminal_id)){
String Terminal_address= ""+ childDataSnapshot.child("address").getValue();
String Terminal_name = ""+ childDataSnapshot.child("terminal_name").getValue();
terminal_name.setText(Terminal_name);
terminal_address.setText(Terminal_address);
}
else {
Toast.makeText(getApplicationContext(),"No Entry matching barcode",Toast.LENGTH_LONG).show();
}
//Log.v(TAG,""+ childDataSnapshot.child("terminal_name").getValue()); //gives the value for given keyname
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}else{
Toast.makeText(getApplicationContext(),"It's null.",Toast.LENGTH_LONG).show();
}
//Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
//get the terminal id for each child then check if it matches the scanned barcode
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Database Structure:
{
"All Machines": {
"-M-JnXkserObKnDj3iZO": {
"address": "OANDO IDIROKO",
"atmClass": "6627",
"bankName": "SPL",
"brand": "NCR",
"id": "-M-JnXkserObKnDj3iZO",
"ip": "1033944",
"latitude": "10333",
"longitude": "10333",
"serial_no": "13528891",
"terminal_Id": "10332368",
"terminal_name": "ATM9"
}
}
}
You can use orderByChild and equalTo methods to filter data in server side like below:
// Get DatabaseReference for All Machines
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("All Machines");
// Use orderByChild to order data by terminal_Id and use equalTo for filter by newTerminal_id
Query query = databaseReference.orderByChild("terminal_Id").equalTo(newTerminal_id);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String Terminal_address= childSnapshot.child("address").getValue(String.class);
String Terminal_name = childSnapshot.child("terminal_name").getValue(String.class);
terminal_name.setText(Terminal_name);
terminal_address.setText(Terminal_address);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Output: If terminal_Id equals 10332368, then
Terminal_address = "OANDO IDIROKO";
Terminal_name = "ATM9";
I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83