说onSucces方法下的Toast可以正常工作,但是onSucces之外的Toast不能正常工作
“ java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String com.example.collegecommune.User.getName()'”
我正在尝试从Firestore获取当前用户数据,并将其存储在自定义类User中。 我想将 documentSnapshot.toObject(User.class)存储在 currentUser 中。
static FirebaseAuth auth = FirebaseAuth.getInstance();
static FirebaseUser cUser = auth.getCurrentUser();
public static User currentUser;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetchProfile();
// currentUser = new FirebaseInteract(this).fetchProfile(cUser);
setupToolbar();
navItemSelected();
// role = currentUser.getRole();
// Toast.makeText(this, currentUser.getName() + "", Toast.LENGTH_SHORT).show();
if (savedInstanceState == null) {
navigationView.setCheckedItem(R.id.home);
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new HomeFragment()).commit();
}
}
public void fetchProfile() {
db.collection("users").document(cUser.getEmail()).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
currentUser = documentSnapshot.toObject(User.class);
Toast.makeText(MainActivity.this, currentUser.getName() + "", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, currentUser.getSemester() + "", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Successfully fetched user profile", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
}
});
Toast.makeText(MainActivity.this, currentUser.getName() + "22", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, currentUser.getSemester() + "22", Toast.LENGTH_SHORT).show();
}
我最近尝试了以下代码: 它也不起作用。
public void fetchProfile(String email) {
final ProgressDialog dialog = new ProgressDialog(activity);
dialog.setMessage("Fetching your profile...");
dialog.show();
db.collection("users").document(email).get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
User user1 = documentSnapshot.toObject(User.class);
Toast.makeText(activity, user1.getEmail() + " 00", Toast.LENGTH_SHORT).show();
MainActivity.setCurrentUser(user1);
dialog.dismiss();
}
}).addOnFailureListener(onFailureListener);
}
答案 0 :(得分:2)
通过查看当前的实现,我可以说-您的MaybeUninit
调用是异步的,并且需要花费一些时间来获取数据并更新onSuccess
对象。
到那时,您在currentUser
块之外的烤面包将执行并尝试从onSuccess
对象获取数据,该对象在该时间点将为 null 。因此,它将抛出currentUser