尝试访问getUid方法Firebase时为Null参考

时间:2019-05-23 18:03:57

标签: java android firebase-authentication

我试图将存储在Firebase实时数据库中的用户信息显示在单独页面上的文本视图中,但是当我运行时,LOGCAT在下面抛出错误。我正在检索为用户存储的唯一ID,但是我想它不是在提取数据。

这是针对一个新的android studio应用程序,该应用程序将用户信息存储在数据库中,并检索到配置文件中,以提取所有信息,例如姓名,电子邮件,学校等。我尝试更改用户和验证用户以进行身份​​验证检查,但无济于事。我猜这是一个简单的修复程序,但我没有看到它。错误在这里。

public class ProfileActivity extends AppCompatActivity {

    //Firebase and Database Stuff
    private FirebaseAuth mAuth;
    private FirebaseUser user; // saying it is never assigned
    private TextView Email;
    private TextView TwoPNum;
private TextView Meal;
private TextView PantherFunds;
private TextView Expiration;
private TextView Campus;
private Button logout;

private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
private DatabaseReference myRef;


// TAG
private static final String TAG = "ProfileActivity";


//declare the database reference object. This is what we use to access the database.


// KEEP AN EYE ON
private String userID = user.getUid();

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

    Email = (TextView) findViewById(R.id.profileEmail);
    TwoPNum = (TextView) findViewById(R.id.profileUid);
    Meal = (TextView) findViewById(R.id.mealsNum);
    PantherFunds = (TextView) findViewById(R.id.pFundsNum);
    Expiration = (TextView) findViewById(R.id.expirationDate);
    Campus = (TextView) findViewById(R.id.campusText);


    //declare the database reference object. This is what we use to access the database.
    mAuth = FirebaseAuth.getInstance();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getReference();
    logout = (Button) findViewById(R.id.button_logout);
    user = mAuth.getCurrentUser();

    mAuthListener = new FirebaseAuth.AuthStateListener() {


        @Override
        public void onAuthStateChanged(FirebaseAuth firebaseAuth) {
            user = firebaseAuth.getCurrentUser();
            if (user != null) {
                // User is signed in
                Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                toastMessage("Successfully signed in with: " + user.getEmail());
            } else {
                // User is signed out
                Log.d(TAG, "onAuthStateChanged:signed_out");
                toastMessage("Successfully signed out.");
            }

           //... I think a method declaration is meant to go here but not sure
        }
    };

    //new stuff
    myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            showData(dataSnapshot);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}

private void showData(DataSnapshot dataSnapshot) {
    for (DataSnapshot ds : dataSnapshot.getChildren()) {
        UserInformation uInfo = new UserInformation();
        uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName()); //set the name
        uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail()); //set the email
        uInfo.setCampus(ds.child(userID).getValue(UserInformation.class).getCampus()); //set the phone_num
        uInfo.setExpiration_date(ds.child(userID).getValue(UserInformation.class).getExpiration_date());// set expiration date
        uInfo.setpfunds(ds.child(userID).getValue(UserInformation.class).getpfunds()); // get pantherfunds
        uInfo.setMeals(ds.child(userID).getValue(UserInformation.class).getMeals()); // get Meals
        uInfo.setTwop_num(ds.child(userID).getValue(UserInformation.class).getTwop_num()); // get Meals

       //display all the information
        Log.d(TAG, "showData: name: " + uInfo.getName());
        Log.d(TAG, "showData: email: " + uInfo.getEmail());
        Log.d(TAG, "showData: campus : " + uInfo.getCampus());
        Log.d(TAG, "showData: expiration_date: " + uInfo.getExpiration_date());
        Log.d(TAG, "showData: pfunds: " + uInfo.getpfunds());
        Log.d(TAG, "showData: : meals" + uInfo.getMeals());
        Log.d(TAG, "showData: twop_num: " + uInfo.getTwop_num());

        // Show Data in TextViews
        Email.append(uInfo.getEmail());
        TwoPNum.append(uInfo.getTwop_num());
        Meal.append(String.valueOf(uInfo.getMeals()));
        PantherFunds.append(String.valueOf(uInfo.getpfunds()));
        Expiration.append(String.valueOf(uInfo.getExpiration_date()));
        Campus.append(uInfo.getCampus());

        }
    }

我希望用户登录并且他们的数据显示在文本视图中,但是会收到此错误消息

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo            
{com.example.hootidapp/com.example.hootidapp.ProfileActivity}: 
java.lang.NullPointerException: Attempt to invoke virtual method         
'java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()' on a 
null object reference

Caused by: java.lang.NullPointerException: Attempt to invoke virtual 
method 'java.lang.String com.google.firebase.auth.FirebaseAuth.getUid()' 
on a null object reference
at com.example.hootidapp.ProfileActivity.<init>(ProfileActivity.java:45)

1 个答案:

答案 0 :(得分:2)

在这一行代码中:

user = mAuth.getCurrentUser();

getCurrentUser()返回null,因为在调用该用户时没有用户登录,并且您正在使用auth,然后auth侦听器才能获取非null用户对象。在调用getUid()上的user之前检查null。或者,确保仅在用户对象可用后才调用它。