我无法弄清楚为什么我的userId
字符串会回来null
。请帮忙。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//get firebase auth instance
auth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
Intent intent = getIntent();
carName = intent.getStringExtra("carname");
//get current user
if (auth.getCurrentUser().getUid() != null) {
userId = auth.getCurrentUser().getUid();
}
authStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.d(TAG, "AUTH STATE SIGNED IN");
userId = user.getUid();
getCarName();
mDatabaseReference.child("cars").setValue(userId);
} else {
//User is Signed out
Log.d(TAG, "AUTH STATE SIGNED OUT");
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
};
auth.addAuthStateListener(authStateListener);
//set views
setContentView(R.layout.activity_main);
final TextView carNameTV = (TextView) findViewById(R.id.car_name);
final TextView carAddressTV = (TextView) findViewById(R.id.car_notes);
final TextView carCountTV = (TextView) findViewById(R.id.count);
plusOneButton = (Button) findViewById(R.id.buttonIn);
minusOneButton = (Button) findViewById(R.id.buttonOut);
signOut = (Button) findViewById(R.id.sign_out_button);
editCar = (Button) findViewById(R.id.edit_car_button);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("cars").child(userId);
我能够通过在侦听器之前添加此if
语句来绕过它。我宁愿不让它看起来那样。任何帮助表示赞赏。
答案 0 :(得分:1)
onAuthStateChanged()回调是异步的。在用户登录之前,不会使用有效的用户ID触发。
声明:
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("cars").child(userId);
在侦听器回调中为userId
分配值之前执行。