Alex Espiritu
Alex Espiritu

Reputation: 45

Firebase Checking if username exists

I am currently developing an android app that only requires the user to sign up once after pressing start. The next time the user opens the application, pressing start will redirect the user to the main game already.

I was able to do this using SharedPreferences. After signing up, I store a value called currentState and I use it to check if the user has already signed up. Here's the code:

   final int currentState = sharedPreferences.getInt(USERSTATE_NUM_KEY,0);
   if(currentState == 0 ) {
          Intent i = new Intent(MainActivity.this, Main_Screen.class);
          startActivity(i);
    } else{
               // Redirect user to tutorial page, then the map page.
    }

Now I was asked to accomplish this again using Firebase since I've already stored the user data.

Here's my code so far just to try if it's going to the onDataChange but it doesn't and I'm not sure how to do it now. Here's my code so far:

final String currentUsername = sharedPreferences.getString(USERNAME_NUM_KEY, "");
final DatabaseReference userNameRef = rootReference.child("users");
startGame.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            userNameRef.orderByChild("username").equalTo(currentUsername)
                    .addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            if(dataSnapshot.exists()){
                                Log.v("TESTERR", "HELLO I EXIST LOL");
                            }
                            else{
                                Log.v("TESTERR", "NEW USER PAGE");
                            }
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });
 }
 });

firebase databasee

Thank you!!!

Upvotes: 1

Views: 2414

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

This:

userNameRef.orderByChild("username").equalTo(currentUsername)

is a query it is like saying where username= currentUsername

The currentUsername is the logged in user, the datasnapshot is users.

So in your database you have:

users
 userid
   username: currentUsername

When you use if(dataSnapshot.exists()){ it checks the snapshot which is users and checks the where condition, if theys exists in the database then it will enter the if clause.

If the where condition does not exists in the database then it will enter the else.

Upvotes: 5

Related Questions