Firebase和毕加索在首次加载时未加载用户信息

时间:2017-05-25 03:46:17

标签: android firebase firebase-authentication picasso

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

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

下面是一些截图,展示我正在谈论的内容: 首次加载:

1

第二次加载后:

2

2 个答案:

答案 0 :(得分:0)

Hello Davis如果有帮助,请在您的代码中尝试此操作 当你的活动第一次加载onCrate方法将工作,而从背景到前景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();
        }
    }

答案 1 :(得分:0)

使用抽屉状态更改侦听器可能会帮助您,这里是您的代码的精简版本,我保持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)编码