Search code examples
androidfirebasefirebase-authenticationpicasso

Firebase and picasso not loading users information on first load


I have a simple project with a navigation drawer that loads the users name, email and profile picture when they log in using a google account, This all gets set in the navigation drawer. The issue I'm facing is that it does not load the users picture, name or email when they first launch the app and log in, if you close the app and reopen it will then show the users information. My code is below:

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.mts2792.swissarmytools.R;
import com.squareup.picasso.Picasso;

import model.CircleTransform;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mAuth = FirebaseAuth.getInstance();

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d("User logged in", "onAuthStateChanged:signed_in:" + user.getUid());
                } else {
                    // User is signed out
                    Log.d("User logged out", "onAuthStateChanged:signed_out");
                }
                // ...
            }
        };

    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        if (user != null) {

            // Name, email address, and profile photo Url
            String name = user.getDisplayName();
            String email = user.getEmail();
            Uri photoUrl = user.getPhotoUrl();

            // The user's ID, unique to the Firebase project. Do NOT use this value to
            // authenticate with your backend server, if you have one. Use
            // FirebaseUser.getToken() instead.
            String uid = user.getUid();

            TextView nameTextView = (TextView) findViewById(R.id.currentUser);
            TextView emailTextView = (TextView) findViewById(R.id.currentEmail);
            ImageView currentPic = (ImageView) findViewById(R.id.currentPic);

            nameTextView.setText(name);
            emailTextView.setText(email);

            Picasso.with(this)
                    .load(photoUrl)
                    .resize(175, 175)
                    .placeholder(R.drawable.ic_account)
                    .error(R.drawable.ic_account)
                    .centerCrop()
                    .transform(new CircleTransform())
                    .into(currentPic);
//            Picasso.with(this).load(photoUrl).into(currentPic);

            Log.v("Logged in", name);
            Log.v("Email: ", email);

        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_home) {
            // Handle the camera action
        } else if (id == R.id.nav_compass) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

Heres some screenshots to show what I'm talking about: First load:

1

After the second load:

2


Solution

  • Using Drawer state change listener might help you out, here is a stripped down version of your code, I have kept the ActionBarDrawerToggle as is., you might want to update that

    public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {
    
     private FirebaseAuth mAuth;
     FirebaseUser FBuser;
     private FirebaseAuth.AuthStateListener mAuthListener;
    
     @Override
     protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
      setSupportActionBar(toolbar);
    
    
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
       this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
      drawer.setDrawerListener(toggle);
      toggle.syncState();
    
      NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
      navigationView.setNavigationItemSelectedListener(this);
    
      mAuth = FirebaseAuth.getInstance();
      FBuser = FirebaseAuth.getInstance().getCurrentUser();
    
      mAuthListener = new FirebaseAuth.AuthStateListener() {
       @Override
       public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
        FBuser = firebaseAuth.getCurrentUser();
        fetchUpdateUserData();
        if (FBuser != null) {
         // User is signed in
         Log.d("User logged in", "onAuthStateChanged:signed_in:" + FBuser.getUid());
        } else {
         // User is signed out
         Log.d("User logged out", "onAuthStateChanged:signed_out");
        }
        // ...
       }
      };
    
      mAuth.addAuthStateListener(mAuthListener)
    
     }
    
     @Override
     public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.main, menu);
    
      // Fetch Data if FBuser is not null
      fetchUpdateUserData();
    
      DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
      drawer.addDrawerListener(new DrawerLayout.DrawerListener() {
       @Override
       public void onDrawerSlide(View drawerView, float slideOffset) {}
    
       @Override
       public void onDrawerOpened(View drawerView) {}
    
       @Override
       public void onDrawerClosed(View drawerView) {}
    
       @Override
       public void onDrawerStateChanged(int newState) {
        // STATE_IDLE, STATE_DRAGGING or STATE_SETTLING.
        if (newState == STATE_DRAGGING || newState == STATE_SETTLING)
        // Fetch Data if FBuser is not null
         fetchUpdateUserData();
       }
      });
    
      drawer.closeDrawer(GravityCompat.START);
    
      return true;
     }
    
    
    
     public void fetchUpdateUserData() {
      if (FBuser != null) {
    
       // Name, email address, and profile photo Url
       String name = FBuser.getDisplayName();
       String email = FBuser.getEmail();
       Uri photoUrl = FBuser.getPhotoUrl();
    
       // The FBuser's ID, unique to the Firebase project. Do NOT use this value to
       // authenticate with your backend server, if you have one. Use
       // FirebaseUser.getToken() instead.
       String uid = FBuser.getUid();
    
       TextView nameTextView = (TextView) findViewById(R.id.currentUser);
       TextView emailTextView = (TextView) findViewById(R.id.currentEmail);
       ImageView currentPic = (ImageView) findViewById(R.id.currentPic);
    
       nameTextView.setText(name);
       emailTextView.setText(email);
    
       Picasso.with(this)
        .load(photoUrl)
        .resize(175, 175)
        .placeholder(R.drawable.ic_account)
        .error(R.drawable.ic_account)
        .centerCrop()
        .transform(new CircleTransform())
        .into(currentPic);
       //            Picasso.with(this).load(photoUrl).into(currentPic);
    
      } else {
       nameTextView.setText("");
       emailTextView.setText("");
       Picasso.with(this)
        .load(R.drawable.ic_account)
        .resize(175, 175)
        .placeholder(R.drawable.ic_account)
        .error(R.drawable.ic_account)
        .centerCrop()
        .transform(new CircleTransform())
        .into(currentPic);
      }
     }
    
    }
    

    PS: please refactor the code before posting and use Fields rather than localVariables for DRY (don't repeat yourself) coding