java - 尝试访问 Firebase getUid 方法时为 Null 引用

标签 java android firebase-authentication

我试图将 Firebase 实时数据库中存储的用户信息显示到单独页面上的 TextView ,但当我运行时,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());

        }
    }

我希望用户登录并且他们的数据显示在 TextView 中,但收到此错误消息

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)

最佳答案

在这行代码中:

user = mAuth.getCurrentUser();

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

关于java - 尝试访问 Firebase getUid 方法时为 Null 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56280716/

相关文章:

java - 是否有用于 Java 的工具可以找到特定 JUnit 测试测试了哪些代码行?

android - 适用于 Android 和 iOS 的数据库格式

java - ViewPager 的 TabLayout 不显示标题

java - Java 函数的参数是否需要可选接口(interface)?

java - 在 JFrame 上定位 JButton 不会显示

Java 使用分隔符拆分字符串

swift - Firebase 评论未出现在数据库中

java - 无法解析方法 get width 和 getHeight

android - 如何使 FirebaseAuth.AuthStateListener 在 Kotlin 中工作?

swift - Firebase 注销然后切换 Storyboard