我试图在我的数据库中保存用户的数据,但我有时会从以下位置获得空值:
currentUser = dataSnapshot.getValue(User.class);
密钥正确指向用户ID,但值为null
这是我的代码:
package com.example.eltobgy.yala;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String ANONYMOUS = "Anonymous";
// Choose an arbitrary request code value
private static final int RC_SIGN_IN = 1;
public static DatabaseReference mDatabaseReference;
public static FirebaseDatabase mDatabase;
public static User currentUser;
// Firebase
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private ChildEventListener mChildEventListener;
private String mUsername;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Signing you in ...");
progressDialog.show();
mUsername = ANONYMOUS;
mFirebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
currentUser = null;
mDatabaseReference = mDatabase.getReference().child("users");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
// User is signed in
onSignedInInitialize(firebaseUser.getDisplayName());
DatabaseReference userDatabaseRefrence = mDatabaseReference.child(firebaseUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(User.class);
progressDialog.dismiss();
if (currentUser.isBasicInfo()) {
if (currentUser.getCurrentType().equals("")) {
Intent intent = new Intent(MainActivity.this, UserTypeActivity.class);
startActivity(intent);
} else if (currentUser.getCurrentType().equals("t")) {
if (!currentUser.isDeliveryModeActivation()) {
Intent intent = new Intent(MainActivity.this, DeliveryManExtraInfoActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, BasicInfoActivity.class);
startActivity(intent);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
};
userDatabaseRefrence.addValueEventListener(valueEventListener);
} else {
// User is signed out
onSignedOutCleanup();
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.setTheme(R.style.LoginTheme)
.build(),
RC_SIGN_IN);
}
}
};
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
User user = new User(firebaseUser.getUid(), firebaseUser.getDisplayName(), firebaseUser.getEmail());
mDatabaseReference.child(user.getId()).setValue(user);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(@NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
//mMessageAdapter.clear();
//detachDatabaseReadListener();
}
@Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}
我的User.java类
package com.example.eltobgy.yala;
import java.io.Serializable;
public class User implements Serializable {
private String id;
private String name;
private String phone;
private String email;
private String photoUrl;
private String currentType; //c for customer, d for delivery man
private boolean deliveryModeActivation;
private int rating;
private String gender; //u:unkown, f:female, m:male
private Birthday birthday;
private boolean basicInfo;
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.phone = "";
this.email = email;
this.currentType = "";
this.deliveryModeActivation = false;
this.rating = 0;
photoUrl = "";
gender = "u";
birthday = new Birthday(0, 0, 0);
basicInfo = false;
}
public User() {
}
public boolean isBasicInfo() {
return basicInfo;
}
public void setBasicInfo(boolean basicInfo) {
this.basicInfo = basicInfo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCurrentType() {
return currentType;
}
public void setCurrentType(String currentType) {
this.currentType = currentType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public boolean isDeliveryModeActivation() {
return deliveryModeActivation;
}
public void setDeliveryModeActivation(boolean deliveryModeActivation) {
this.deliveryModeActivation = deliveryModeActivation;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}