Skip to content Skip to sidebar Skip to footer

How To Avoid The Overwriting Without Using .push() In Firebase? Using The Autoincrement To Generate Id To Replace .push()

I try to generate the ID(autoincrement) to replace the unique ID. Could somebody help me to solve this problem? Thank you! public void SignUp(){ int UserCount = 1; String

Solution 1:

If you really want to avoid using push() method, then you need to retrieve all users from your database before setting the value.

Here's how to do that

userRef.addListenerForSingleValueEvent(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        int count = dataSnapshot.getChildrenCount() + 1;
        String identifier = "User" + count;

        // save the new user
        userRef.setValue( ... );
    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {

    }
});

Solution 2:

You can try this:

finalDatabaseReferencefirebaseRef= FirebaseDatabase.getInstance().getReference();
finalDatabaseReferencemCounterRef= firebaseRef.child("counter");
// listen for single change
mCounterRef.addListenerForSingleValueEvent(newValueEventListener() {
    @OverridepublicvoidonDataChange(DataSnapshot dataSnapshot) {
        // getValue() returns Longlongcount= (long) dataSnapshot.child("Users").getValue();

        System.out.println("count before setValue()=" + count);

        mCounterRef.child("count").setValue(++count);  // <= Change to ++count

        System.out.println("count after setValue()=" + count);

    }

    @OverridepublicvoidonCancelled(DatabaseError databaseError) {
        // throw an error if setValue() is rejectedthrow databaseError.toException();
    }
});

If the app crashed while running then you should add this part:

mCounterRef.child("users").setValue(++count, newDatabaseReference.CompletionListener() {
        @OverridepublicvoidonComplete(DatabaseError databaseError,
                           DatabaseReference databaseReference) {
            if (databaseError != null) {
                System.out.println("Error: " + databaseError.getMessage());
            }
        }
    });

Post a Comment for "How To Avoid The Overwriting Without Using .push() In Firebase? Using The Autoincrement To Generate Id To Replace .push()"