title: Check if is user first login on Android App using Firebase Auth and Database
body: <p><strong>I am making an chat app and I want to do the following:</strong></p>
  
  <p>When starting the MainActivity, check if the user is logged in. If not, start FirebaseAuthUI.</p>
  
  <p>But FirebaseAuth only supports a few parameters and, to add more, I created a Database node do each user, which store other parameters. 
  To get this parameters, after finishing FirebaseAuth, the user is redirected to an Activity that get all extra information and store in the user's node in the Database. All of this is working just fine.</p>
  
  <p>But after the user fill the information in this Info Activity and finish the register, it should go back to MainActivity and stay there. How can I do that?</p>
  
  <p><strong>I am trying it this way:</strong></p>
  
  <p>I added to each user a Boolean variable called <code>userCompleted</code>, which informs if the user have already gave their information. I check if this variable is false, and if so, I call the Info Activity intent and, in the when the user press the button to complete the registration in this Activity, it sets the <code>userCompleted</code> value to <code>true</code> in the user node in the Database and then start an intent that leads to MainActivity.</p>
  
  <p>The problem is that in the Database, <code>userCompleted</code> is set to <code>true</code> and then immediately goes back to <code>false</code>, and I don't know why. Also, I guess I am having trouble on reading <code>userCompleted</code> from the Database, probably because I haven't worked much with asynchronous tasks.</p>
  
  <p>I used a variable <code>isUserCompleted</code> declared in Main Activity to get track of the userCompleted value.</p>
  
  <p>A way to check if is the first time the user is logging in would be useful too, although it wouldn't solve my whole problem.</p>
  
  <p><strong>This is my current code:</strong> </p>
  
  <p>(if need more to try to understand the problem just ask in the comments)</p>
  
  <p><em>Create AuthStateListener</em></p>
  
  <pre><code>public void setAuthStateListener(){
      mAuthStateListener = new FirebaseAuth.AuthStateListener() {
          @Override
          public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
              FirebaseUser user = firebaseAuth.getCurrentUser();
  
              if (user != null) {
                  onSignInInitialize(user);
                  Log.d(TAG, "userUid = " + user.getUid());
                  Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
              } else {
                  onSignOutCleanup();
                  startLoginUI();
              }
          }
      };
  }
  </code></pre>
  
  <p><em>onSignInInitialize()</em></p>
  
  <pre><code>public void onSignInInitialize(final FirebaseUser user){
      mLoggedFBUser = user;
      mUserReference = mUsersDatabaseReference.child(user.getUid());
      mUserReference.child("uid").setValue(user.getUid());
  
      mUserReference.addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
              User user = dataSnapshot.getValue(User.class);
              isUserCompleted = user.isUserCompleted();
              Log.d(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
          }
  
          @Override
          public void onCancelled(@NonNull DatabaseError databaseError) {
  
          }
      });
  
      Log.d(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
  
      if (!isUserCompleted) {
          startCreateProfileActivity(user);
      }
      Log.d(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
  
      mUserReference.child("username").setValue(user.getDisplayName());
      mUserReference.child("email").setValue(user.getEmail());
  
      attachChildEventListener();
  }
  </code></pre>
  
  <p><em>Go back to Main Activity</em></p>
  
  <pre><code>mFinishButton.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
              mUserDatabaseReference.child("userCompleted").setValue(true);
              Intent intent = new Intent (CreateVolunteerProfile.this, SearchActivity.class);
              startActivity(intent);
          }
      });
  </code></pre>
  
  <hr>
  
  <p><strong>Entire MainActivity block (Actually it's called <code>SearchActivity</code>)</strong></p>
  
  <pre><code>public class SearchActivity extends AppCompatActivity implements RecyclerAdapter.UserItemClickListener {
  private RecyclerView recyclerView;
  private RecyclerView.Adapter adapter;
  private RecyclerView.LayoutManager layoutManager;
  private ArrayList&lt;User&gt; users = new ArrayList&lt;User&gt;();
  
  private String mLoggedUserId = "user2";
  private String mLoggedUsername;
  private User mLoggedUser;
  private FirebaseUser mLoggedFBUser;
  //private boolean isUserCompleted;
  
  private SharedPreferences mSharedPreferences;
  private SharedPreferences.Editor mPreferencesEditor;
  private boolean firstTime = true;
  
  private static final String TAG = "Search Activity";
  private static final int USER_CLICK = 1;
  
  private static final int RC_SIGN_IN = 1;
  private static final int RC_CREATE_PROFILE = 2;
  
  //Firebase
  private FirebaseDatabase mFirebaseDatabase;
  private DatabaseReference mUsersDatabaseReference;
  private DatabaseReference mUserReference;
  private ChildEventListener mChildEventListener;
  private FirebaseAuth mFirebaseAuth;
  private FirebaseAuth.AuthStateListener mAuthStateListener;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_search);
  
      View loadingView = findViewById(R.id.cl_loading);
      loadingView.setVisibility(View.VISIBLE);
  
      //RecyclerView
      recyclerView = findViewById(R.id.rv_users);
      recyclerView.setHasFixedSize(true);
  
      layoutManager = new LinearLayoutManager(this);
      recyclerView.setLayoutManager(layoutManager);
  
      adapter = new RecyclerAdapter(users, this);
      recyclerView.setAdapter(adapter);
  
      //Firebase
      mFirebaseDatabase = FirebaseDatabase.getInstance();
      mFirebaseAuth = FirebaseAuth.getInstance();
      mUsersDatabaseReference = mFirebaseDatabase.getReference().child("users");
  
      setAuthStateListener();
  
      loadingView.setVisibility(View.GONE);
  }
  
  @Override
  protected void onResume() {
      super.onResume();
      mFirebaseAuth.addAuthStateListener(mAuthStateListener);
  }
  
  @Override
  protected void onPause() {
      super.onPause();
      if (mAuthStateListener != null)
          mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
      detachChildEventListener();
      clearAdapter();
  }
  
  @Override
  protected void onSaveInstanceState(Bundle outState) {
      Log.wtf(TAG, "onSaveInstanceState userId = "+ mLoggedUserId);
      //Log.wtf(TAG, "UserCompleted (onSaveInstanceState) " + isUserCompleted);
      outState.putString("userId", mLoggedUserId);
      //outState.putBoolean("isUserCompleted", isUserCompleted);
      super.onSaveInstanceState(outState);
  }
  
  @Override
  protected void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      mLoggedUserId = savedInstanceState.getString("userId");
      //isUserCompleted = savedInstanceState.getBoolean("isUserCompleted");
      //Log.wtf(TAG, "UserCompleted (onRestoreInstanceState) " + isUserCompleted);
      Log.wtf(TAG, "onRestoreInstanceState userId = "+ mLoggedUserId);
  
  }
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
  
      if((requestCode == RC_SIGN_IN) &amp;&amp; firstTime){
          if (resultCode == RESULT_OK){
              //Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
          } else if (resultCode == RESULT_CANCELED){
              Toast.makeText(this, "Sign in canceled!", Toast.LENGTH_SHORT).show();
              finish();
          }
      }
  
      if((requestCode == RC_CREATE_PROFILE)){
          if (resultCode == RESULT_OK){
              //isUserCompleted = true;
          }
      }
  }
  
  @Override
  public void onUserItemClick(int clickedUserIndex) {
      Intent intent = new Intent (this, ChatActivity.class);
  
      FirebaseUser user = mFirebaseAuth.getCurrentUser();
  
      if(user !=  null) {
          mLoggedUserId = user.getUid();
          intent.putExtra("user1", mLoggedUserId);
  
          String mUserRecieverId = users.get(clickedUserIndex).getUid();
          intent.putExtra("user2", mUserRecieverId);
  
          Log.wtf(TAG, "SearchActivity // user = " + users.get(clickedUserIndex));
          Log.wtf("1", "SearchActivity // mLoggedUserId = " + mLoggedUserId + " // users.getUid() = " + users.get(clickedUserIndex).getUid());
  
          startActivityForResult(intent, USER_CLICK);
      }
      else {
          Toast.makeText(this, "ERROR", Toast.LENGTH_SHORT).show();
      }
  
  }
  
  public void setAuthStateListener(){
      mAuthStateListener = new FirebaseAuth.AuthStateListener() {
          @Override
          public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
              FirebaseUser user = firebaseAuth.getCurrentUser();
  
              if (user != null) {
                  mUserReference = mUsersDatabaseReference.child(user.getUid());
                  onSignInInitialize(user);
  
                  Log.wtf(TAG, "userUid = " + user.getUid());
  
                  Toast.makeText(SearchActivity.this, "Signed in!", Toast.LENGTH_SHORT).show();
              } else {
                  onSignOutCleanup();
                  startLoginUI();
              }
          }
      };
  }
  
  public void onSignInInitialize(final FirebaseUser user){
      mLoggedFBUser = user;
      mUserReference = mUsersDatabaseReference.child(user.getUid());
      mUserReference.child("uid").setValue(user.getUid());
      boolean isUserCompleted = false;
  
      mUserReference.addValueEventListener(new ValueEventListener() {
          @Override
          public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
              User user = dataSnapshot.getValue(User.class);
              isUserCompleted = user.isUserCompleted();
              Log.wtf(TAG, "UserCompleted (onDataChanged) "+ isUserCompleted);
          }
  
          @Override
          public void onCancelled(@NonNull DatabaseError databaseError) {
  
          }
      });
  
      Log.wtf(TAG, "UserCompleted (Before startActivity if) "+ isUserCompleted);
  
      if (!isUserCompleted) {
          startCreateProfileActivity(user);
      }
      Log.wtf(TAG, "UserCompleted (After startActivity if) "+ isUserCompleted);
  
      mUserReference.child("username").setValue(user.getDisplayName());
      mUserReference.child("email").setValue(user.getEmail());
  
      attachChildEventListener();
  }
  
  public void onSignOutCleanup(){
      mLoggedUser = null;
      mLoggedUserId = null;
      mLoggedUsername = null;
      detachChildEventListener();
      clearAdapter();
  }
  
  public void attachChildEventListener(){
      if (mChildEventListener == null){
          mChildEventListener = new ChildEventListener() {
              @Override
              public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                  User user = dataSnapshot.getValue(User.class);
                  users.add(user);
                  Log.d(TAG, "onChildAdded userId = "+ user.getUid());
                  //adapter.notifyItemInserted(users.size()-1);
                  adapter.notifyDataSetChanged();
              }
              @Override
              public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
              @Override
              public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) { }
              @Override
              public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) { }
              @Override
              public void onCancelled(@NonNull DatabaseError databaseError) { }
          };
      }
  
      mUsersDatabaseReference.addChildEventListener(mChildEventListener);
  }
  
  public void detachChildEventListener(){
      if (mChildEventListener != null){
          mUsersDatabaseReference.removeEventListener(mChildEventListener);
          mChildEventListener = null;
      }
  }
  
  public void clearAdapter() {
      final int size = users.size();
      if (size &gt; 0) {
          for (int i = 0; i &lt; size; i++) {
              users.remove(0);
          }
          adapter.notifyItemRangeRemoved(0, size);
      }
  }
  
  public void startCreateProfileActivity(FirebaseUser user){
      mUsersDatabaseReference.child(user.getUid()).child("userCompleted").setValue(false);
      Intent intent = new Intent(SearchActivity.this, CreateProfileActivity.class);
      intent.putExtra("userId", user.getUid());
      startActivityForResult(intent, RC_CREATE_PROFILE);
  }
  
  public void startLoginUI(){
      startActivityForResult(
              AuthUI.getInstance()
                      .createSignInIntentBuilder()
                      .setIsSmartLockEnabled(false)
                      .setLogo(R.mipmap.logo)
                      .setAvailableProviders(Arrays.asList(
                              new AuthUI.IdpConfig.GoogleBuilder().build(),
                              //new AuthUI.IdpConfig.FacebookBuilder().build(),
                              //new AuthUI.IdpConfig.TwitterBuilder().build(),
                              //new AuthUI.IdpConfig.GitHubBuilder().build(),
                              new AuthUI.IdpConfig.EmailBuilder().build()))
                      //new AuthUI.IdpConfig.PhoneBuilder().build(),
                      //new AuthUI.IdpConfig.AnonymousBuilder().build()))
                      .build(),
              RC_SIGN_IN);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater menuInflater = getMenuInflater();
      menuInflater.inflate(R.menu.search_menu, menu);
      return true;
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()){
          case R.id.sign_out_item:
              AuthUI.getInstance().signOut(this);
              return true;
  
          default:
              return super.onOptionsItemSelected(item);
      }
  }
  </code></pre>
  
  <p>}</p>