【发布时间】:2019-09-16 02:27:06
【问题描述】:
onSucces 方法下的 Toast 可以工作,但 onSucces 之外的 Toast 不工作是说
“java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'java.lang.String com.example.collegecommune.User.getName()'”
我正在尝试从 Firestore 中获取当前用户数据并将其存储在自定义类 User 中。 我想在 currentUser 中存储 documentSnapshot.toObject(User.class)。
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);
}
【问题讨论】:
-
您的代码格式似乎不正确。您要编辑问题并更正吗?
-
您的代码格式不正确。请更正。如果您的配置文件提取失败,则通过查看当前实现,您的 currentUser 对象将为空,因此会出现错误。
标签: java android nullpointerexception google-cloud-firestore