How to check Already existing data in firebase database - java

I want to check that if classection=Six:B already exist in firebase database then it show toast message please guide I am trying to solve this from 3 days but I cannot solve it Here is my code it doesnot show any error or toast
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
Query query = ref.child("Students");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String classsection=""+dataSnapshot.child("classsection").getValue();
if(classsection.equals("Six:B"))
{
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist",
Toast.LENGTH_LONG).show();
}
else
{
// updateclasfiveb();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MaintabclasActivity.this, "error",
Toast.LENGTH_LONG).show();
}
});

Instead of addListenerForSingleValueEvent ,use onCompleteListener to get data once if you really wants access real time database. because addListenerForSingleValueEvent is for cache data.
// If you have child node id to go through each node use below method.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users");
ref.child("Students").child("node_id_under_student").get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
// Or use query method with ValueEventListener to listen for changes in database.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/Students");
Query databaseQuery= ref.orderByChild("classsection").equalTo("Six:B");
databaseQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot: dataSnapshot.getChildren()) {
String classsection=""+dataSnapshot.child("classsection").getValue();
if(classsection.equals("Six:B"))
{
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist",
Toast.LENGTH_LONG).show();
}
else
{
// updateclasfiveb();
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});

A query in Firebase consists of two parts:
A call to order the child nodes of a path on its key, or a certain property.
A call to then filter the child nodes down by a certain value or range.
In your case:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Users/Students");
Query query = ref.orderByChild("classsection").equalTo("Six:B");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()) {
Toast.makeText(MaintabclasActivity.this, "Class Six B is Already Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MaintabclasActivity.this, "error", Toast.LENGTH_LONG).show();
}
});

Related

Check value of child in Firebase DB Java

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();
}

My Firebase is not retrieving data from Firebase Database

I have seen many other similar questions and also tried their method but still its not working.
My getFirebase function on a Click Listener :
private void getFirebase() {
firebaseDatabase = FirebaseDatabase.getInstance();
reference = firebaseDatabase.getReference().child("Questions/m1");
List<String> list = new ArrayList<>();
Log.d("QuizFragment", "getfirebase");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("QuizFragment", " Snapshots");
list.add(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("QuizFragment", "error " + databaseError.toString());
}
});
Log.d("QuizFragment","debug");
}
My Logcat is showing getFirebase and then directly debug message.
I have seen many answer to wait for execution of SingleEvent but I have waited for many time still its not showing. Note : I am running app on emulator
addListenerForSingleValueEvent will get the data from the local disk cache.If you don't have any data in your cache you won't get any data.i believe that's why you could not get into onDataChange(). so first get data at least once like this
firebaseDatabase.getReference().child("Questions/m1")
.get()
.addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else {
Log.d("firebase", String.valueOf(task.getResult().getValue()));
}
}
});
//then use cache data.
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d("QuizFragment", " Snapshots");
list.add(dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("QuizFragment", "error " + databaseError.toString());
}
});

How to check for a specific value exist in the firebase realtime database?

I am trying to write a query to check if there is any "Pending" status on mcustDeliveryStatus. I want to check in Order node that is there any Pending status for mcustDeliveryStatus.
I wrote the following query
mDatabase = FirebaseDatabase.getInstance().getReference("Order");
final Query query = mDatabase.OrderByChild("mcustDeliveryStatus").equalTo("Pending");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Toast.makeText(VWelcome.this, "new order", Toast.LENGTH_LONG).show();
Intent i = new Intent(VWelcome.this, ViewOrderRequest.class);
startActivity(i);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This query works fine but the problem is intent runs even when there is no Pending status in my Order node. Anyone knows why?
Since you annotate your DataSnapshot object with #NonNull, it means that you tell the compiler that your object cannot be null, so it will always return something. With other words, if there are no results, it will return an empty DataSnapshot object. To solve this, you should check how many children are inside that object using the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference orderRef = rootRef.child("Order");
Query query = orderRef.orderByChild("mcustDeliveryStatus").equalTo("Pending");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long count = dataSnapshot.getChildrenCount();
if (count > 0) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String mGasBand = ds.child("mGasBand").getValue(String.class);
Log.d(TAG, mGasBand);
}
} else {
Log.d(TAG, "No data!");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);

Shortest Query of Firebase in Android?

I need to check if conversation child is exist.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild("conversations")) {
if (snapshot.child("conversations").hasChild(receiverId)) {
ConversationLocationModel conversationModel = snapshot.child("conversations").child(receiverId).getValue(ConversationLocationModel.class);
roomId = conversationModel.getLocation();
getAllMessage();
} else {
addinLocation();
}
} else {
addinLocation();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Currently I am using above code to check if child has exist i do not want to check every time so how it can be possible if there is any child exist is there any query for checking child existence.
If you want to check if any child exists, then you can do this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("users").child(senderId).child("conversations");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.exists()){
//checks if this snapshots exists
}else{
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You can change it depending on your database. But the above will check child("users").child(senderId).child("conversations") if conversations exists then it will enter it and see all its children.

Firebase - check if value exists in database

If the user is authenticated the first time I want to create a new database entry. Therefore I want to to check if the user has already an entry. I searched for some examples but my solutions are not working. My callbacks are never called. Any ideas?
if (firebaseUser == null) {
startActivityForResult(new Intent(this, AuthActivity.class), 123);
} else {
final DatabaseReference database = FirebaseDatabase
.getInstance()
.getReference()
.child("users")
.child(firebaseUser.getUid());
database.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.d(TAG, "onDataChange: ye");
} else {
Log.d(TAG, "onDataChange: fuuu...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: " + databaseError.getMessage());
}
});
}

Categories