Firebase 和 picasso 没有在第一次加载时加载用户信息

Firebase and picasso not loading users information on first load

我有一个带有导航抽屉的简单项目,当用户使用 google 帐户登录时加载用户名、电子邮件和个人资料图片,这些都在导航抽屉中设置。我面临的问题是,当用户首次启动应用程序并登录时,它不会加载用户图片、姓名或电子邮件,如果您关闭应用程序并重新打开,它将显示用户信息。我的代码如下:

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;
    }
}

下面是一些屏幕截图来说明我在说什么: 首次加载:

第二次加载后:

你好,戴维斯,如果有帮助,请在你的代码中试试这个 当您的 activity 首次加载 onCrate 方法时,onResume 方法将起作用,而从后台转到前台时,onResume 将起作用

 @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getUserDetails();

        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);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getUserDetails();
    }

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

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

使用抽屉状态更改侦听器可能会帮助您,这是您的代码的精简版本,我保持原样 ActionBarDrawerToggle。您可能想要更新它

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:请在发布前重构代码并使用 Fields 而不是 localVariables 用于 DRY (don't repeat yourself) 编码