Firebase - check if value exists in database - java

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

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

How to check Already existing data in firebase database

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

dataSnapshot could not get parent push key value

I want dataSnapshot to check if "month" exists in its parent's "summary". But dataSnapshot is returning that it does not have "month" in "summary"
ds = FirebaseDatabase.getInstance().getReference("summary");
ds.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//summary
String key = ds.getKey();
if (dataSnapshot.hasChild("month")) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
My Firebase Database: I want to check the value (blue line) from its parent(red line)
My Firebase Database
The following line of code:
String key = ds.getKey();
Returns the key of the node on which the reference is pointing to, in this case summary. Between the summary node and the month property, there is another level in your structure, which actually is that pushed key (-MJKC ... xGZX). In order to check if that property exists, you need to use that key in the reference too. Assuming that the summary node is a direct node of your Firebase database root, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference keyRef = rootRef.child("summary").child("-MJKC_JkVFpCdCGqxGZX");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("month")) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
However, you haven't store that key into a variable, then you should use a query, as below:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference summaryRef = rootRef.child("summary");
Query queryByMonth = summaryRef.orderByChild("month")
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(newTransaction.this, "got value", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(newTransaction.this, "No value", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
queryByMonth.addListenerForSingleValueEvent(valueEventListener);

Firebase listener not getting called

I want to check whether node is created or not. I just implemented below called with Toast but nothing toasting at all.
note: firebase DataBase is Total null now
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(RegisterActivity.this, dataSnapshot.getKey() + "", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(RegisterActivity.this, databaseError.toString() + "", Toast.LENGTH_SHORT).show();
}
});
secondly below code i tried but no luck
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("device_id");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Toast.makeText(RegisterActivity.this, dataSnapshot.getKey() + "", Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(RegisterActivity.this, databaseError.toString() + "", Toast.LENGTH_SHORT).show();
}
});
Change this line of code:
reference.addListenerForSingleValueEvent(new ValueEventListener() {
with:
reference.child("device_id").addListenerForSingleValueEvent(new ValueEventListener() {

How to move Firebase child from one node to another in Android?

I am working on a project where user request for our valet services and on the other end valet accepts request.
I am using using Firebase as backend and on request customer uid is save on 'request' child.
When valet accepts request, customer uid should move from 'request' node to 'on progress' node.
How can i do that?
I recommend using this :
public void moveFirebaseRecord(Firebase fromPath, final Firebase toPath)
{
fromPath.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
toPath.setValue(dataSnapshot.getValue(), new Firebase.CompletionListener()
{
#Override
public void onComplete(FirebaseError firebaseError, Firebase firebase)
{
if (firebaseError != null)
{
System.out.println("Copy failed");
}
else
{
System.out.println("Success");
}
}
});
}
#Override
public void onCancelled(FirebaseError firebaseError)
{
System.out.println("Copy failed");
}
});
}
This come from this source : https://gist.github.com/katowulf/6099042 . I used it several times in my JavaEE code and also in my android app.
You pass your fromPath and toPath. This is a copy tought and not a move, so the original will remain at his original place too. If you would like to delete, you can do a set value on the fromPath just after the System.out.println("Success"); .
As of compile firebase-database:11.0.1, this is the same function with the new class references (https://firebase.google.com/support/guides/firebase-android July 05 2017)
private void moveGameRoom(final DatabaseReference fromPath, final DatabaseReference toPath) {
fromPath.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference firebase) {
if (firebaseError != null) {
System.out.println("Copy failed");
} else {
System.out.println("Success");
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
If you want to perform a move which also erases the original, you might make use of the following snippet:
// In this piece of code, "fromPath" and "toPath" parameters act like directories.
private void removeFromFirebase(final DatabaseReference fromPath, final DatabaseReference toPath, final String key) {
fromPath.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
// Now "DataSnapshot" holds the key and the value at the "fromPath".
// Let's move it to the "toPath". This operation duplicates the
// key/value pair at the "fromPath" to the "toPath".
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
toPath.child(dataSnapshot.getKey())
.setValue(dataSnapshot.getValue(), new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Log.i(TAG, "onComplete: success");
// In order to complete the move, we are going to erase
// the original copy by assigning null as its value.
fromPath.child(key).setValue(null);
}
else {
Log.e(TAG, "onComplete: failure:" + databaseError.getMessage() + ": "
+ databaseError.getDetails());
}
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, "onCancelled: " + databaseError.getMessage() + ": "
+ databaseError.getDetails());
}
});
}
you can listen to value event on your child you want to copy it ,, and #onDataChange get reference of new child and set value dataSnapshot to this child like below sample code
FirebaseDatabase.getInstance().getReference("childYouWantToCopy")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
FirebaseDatabase.getInstance().getReference("ChildCopyTo").setValue(dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Categories