How to Check If a Value Exists Already in a Firebase Data Class Android

How can I check if a value exists already in a Firebase data class Android

Your approach is wrong.

When you are doing this dataSnapshot.child(busNum).exists(), it's looking for the busNum in the key section, where your keys are -kasajdh....

So instead what you can do is, get the iterable, now when you look for
data.child(busNum).exists() it relates to the value

   postRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
if (data.child(busNum).exists()) {
//do ur stuff
} else {
//do something if not exists
}
}
}

@Override
public void onCancelled(FirebaseError firebaseError) {

}
});

How to check if a value exists already in a Firebase and get key in android

You're attaching a value listener to the root of your database. Then in your onDataChange you loop over the child node, which means that your ds snapshot is for the Users node, while you seem to think it's for the Employee and Customers node.

The fix should be to listen to the Users node instead:

rootRef.child("Users").addListenerForSingleValueEvent(eventListener);

Your current approach is highly inefficient, as (even when you fix the above) you're loading the entire Users node to check if a specific user exists in there. As you add more users to the app, this means you're loading more and more data, without using it.

A better approach is to check whether the specific user exists under each specific node:

rootRef.child("Users/Employee").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
... handle the Employee
}
else {
rootRef.child("Users/Customer").child(user_id).addListenerForSingleValueEvent(new new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
... handle the Customer
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Check if some key value exists in Firebase Database and do some action Android

After a long time, my brain light burned and I came up with a solution.

Create a data class for OrderState

public class OrderState {
public static int ordersCount = 0;

public static boolean state = false;

public static void update(boolean state){
if (state){
ordersCount = ordersCount + 1;
OrderState.state = true;
}else
if (!state && ordersCount > 0){
ordersCount = ordersCount - 1;
if (ordersCount < 1) OrderState.state = false;
}
}

public static void reset(){
ordersCount = 0;
state = false;
}
}

On FirebaseRecyclerAdapter -> onBindViewHolder

//if order not canceled or completed. it will update OrderState, 
//ordersCount + 1 and state to true

if (adminOrders.getState().equals(Prevalent.orderStateNew) ||
adminOrders.getState().equals(Prevalent.orderStateApproved) ||
adminOrders.getState().equals(Prevalent.orderStateShipped) ||
adminOrders.getState().equals(Prevalent.orderStateApproved)){
OrderState.update(true);
}

changeUserWithOrderState();

On changing state of order by admin

//if the order is not already cancelled or completed, reduce one order from OrderState as it will be readded automatically upon Recycler refresh.

if (!adminOrders.getState().equals(Prevalent.orderStateCanceled) &&
!adminOrders.getState().equals(Prevalent.orderStateCompleted)) OrderState.update(false);

Al last if the user does not has any order with states New, Approved, and Shipped
OrderState.orderCount = 0;
OrderState.state = false;
and upon updating the database it will set the state to false.

private void changeUserWithOrderState() {
DatabaseReference userWithOrder = FirebaseDatabase.getInstance().getReference()
.child(Prevalent.usersWithOrders)
.child(userPhoneKey);


HashMap<String, Object> map = new HashMap<>();
map.put(Prevalent.orderState, String.valueOf(OrderState.state));
userWithOrder.updateChildren(map).addOnCompleteListener(task -> {
//Changed state based upon OrderState.state value...
});
}

How to check if value exists in firebase with android?

Please try below code may help you

public void setData(){
final DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
Query queryToGetData = dbRef.child("Biodata")
.orderByChild("Email").equalTo("MyUser@email.com");
queryToGetData.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()){
String userId = dbRef.child("Biodata").push().getKey();
Biodata bio = new Biodata("MyUser", "MyUser@email.com");
dbRef.child("Biodata").child(userId).setValue(bio);
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});
}

How to check if a value exists in firebase

Try this:

boolean CheckExists =false;   //declare and assign default value in global scope

reference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> userChildren = dataSnapshot.getChildren();

for (DataSnapshot user: userChildren) {
User u = user.getValue(User.class); //make a model User with necessary fields

if(u.email.equalsIgnoreCase(Email.getText().toString())){
CheckExists =true;
}
}
}

@Override
public void onCancelled(@NonNull DatabaseError databaseError) {

}
});

Checking if a particular value exists in the Firebase database

To check the existence of a user, please use the below code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userNameRef = rootRef.child("Users").child("Nick123");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.exists()) {
//create new user
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
userNameRef.addListenerForSingleValueEvent(eventListener);

You can also use a Query to achieve the same thing like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Users").orderByChild("userName").equalTo("Nick123");
query.addValueEventListener(/* ... */);

This is another approach which is looping through the entire Users node but is not just using a direct reference to a single user. This option is more likely to be used when you are using as a unique identifier beteeen users the uid instead of the user name (as you do right now). So if your database structure might looks similar to this:

Firebase-root
|
--- Users
|
--- uid
|
--- userName: "Test User"
|
--- emailAddress: "user@email.com"

The second solution is the recommended one.

There is also another solution which involves you to create another node named userNames, in which you can hold only the unique user names. Please also find below the corresponding security rules:

"Users": {
"$uid": {
".write": "auth !== null && auth.uid === $uid",
".read": "auth !== null && auth.provider === 'password'",
"userName": {
".validate": "
!root.child('userNames').child(newData.val()).exists() ||
root.child('userNames').child(newData.val()).val() == $uid"
}
}
}

But since in this case, your user name is already the name of the node, I recommend you go ahead with the first one.

Check if a perticular value exist in Firebase Database

As per Hussain Answer. addValueEventListener() is called each time there is changes in Your Database to overcome this situation you can call addListenerForSingleValueEvent(). Which will called once.

Other than that there is no Get option in Realtime Database

databaseReference.orderByChild("regNo").equalTo(regNo)
.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
//Do what you want to try
}else{
//Create New Node in Database
}
}

@Override
public void onCancelled(DatabaseError databaseError) {

}
});

Check value already exists or not in Firebase?

In your current structure you can check how often the university name already exists as a value under /Universities with a query like this:

String name = "Comsats";
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Universities");
ref.orderByValue().equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Firebase", "There are "+dataSnapshot.getChildrenCount()+" universities named "+name);
for (DataSnapshot universitySnapshot: dataSnapshot.getChildren()) {
Log.i("Firebase", universitySnapshot.getKey+": "+universitySnapshot.getValue(String.class));
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Or just to check if it exist at all, this would be slightly simpler/faster:

ref.orderByValue().equalTo(name).limitToFirst(1).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Log.i("Firebase", "University "+name+" already exists");
}
}

@Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

If you use the above however to then add the university, you end up with a race condition. While one client is checking whether the name already exists, another might be adding it. Since the operations are not guaranteed to be in the order you'd like them, you could still end up with two universities with the same name.

The only way to prevent this is to use the university name as the key* of the nodes instead of as the value. Your structure would become:

"Universities": {
"University of Haripu": true,
"Comsats": true,
"UET": true
}

Node keys are guaranteed to be unique under a certain location, as there's no way to insert a second child node with the same name. So with this structure you automatically guarantee your uniqueness requirement in the data structure.

The true values have no specific meaning in the above structure, and are just there because Firebase can't store a key without a value. If you have a more meaningful value, you can use that too. In fact, you may have to do that....


Firebase has a few characters that are not allowed to be present in a node key, which are allowed in the values. If your values may have such values, you'll want to perform some encoding from the value the user entered to the key that you store for the university.

Two common encodings are:

  1. Remove the offending characters from the string.
  2. Use the hashcode of the string.

The first approach leads to more recognizable keys, so I'll use that here. In practice the second approach is usually better and simpler in code, as hashing is pretty standard functionality these days while other encodings are likely going to be custom for your use-case or Firebase.

In both cases, you'll then want to store the actual value the user entered. So say that spaces and uppercase characters aren't allowed for keys (they are both allowed, so this is just an illustrative example), you'd end up with:

"Universities": {
"universityofharipu": "University of Haripu",
"comsats": "Comsats",
"uet": "UET"
}

Guaranteeing uniqueness has been covered quite a few times before, so I recommend checking out these:

  • Firebase android : make username unique
  • How to avoid duplicate data in Firebase Database
  • Rule entries duplicates firebase not working, which contains links to more questions about uniqueness


Related Topics



Leave a reply



Submit