如何获取AndroidJava中onSuccess方法外的值?

How to get the value outside the onSuccess method in Android Java?

我需要在 Android Java 中的 onSuccess 方法之外获取 userRole。如何得到它? 我尝试实现接口和回调函数,但也没有用。

documentReference = firebaseFirestore.collection(
                "Users").document(firebaseAuth.getCurrentUser().getUid());
        documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
@Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
        userRole = documentSnapshot.getString("userRole");

    }
});

您可以使用两个选项。第一个是使用 Mutablelivedata,第二个是使用接口。假设您使用的是 MVVM 模式。

public Mutablelivedata<String> getuserRole(){
  documentReference = firebaseFirestore.collection("Users").document(firebaseAuth.getCurrentUser().getUid());
  documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
  @Override
  public void onSuccess(DocumentSnapshot documentSnapshot) {
      userRole.setValue(documentSnapshot.getString("userRole"));
    }
 });
return userRole;
}

然后在你的 activity/fragment

yourViewModel.getuserRole.observe(getViewLifecycleOwner(), new new Observer<String>(){
@Overrride
public void onChanged(String s){
//Log.d(TAG, "onChanged: your user role: "+s);
  }
});

二是接口回调

public interface UserRoleInterface(){
  void userRole(String role);
}

然后在你的 method/function

上将接口设置为参数
public void userRole(UserRoleInterface userRoleInterface){
 documentReference = firebaseFirestore.collection("Users").document(firebaseAuth.getCurrentUser().getUid());
 documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
  @Override
  public void onSuccess(DocumentSnapshot documentSnapshot) {
  userRoleInterface.userRole(documentSnapshot.getString("userRole"));
 }
});

然后在你的 Activity/Fragment

yourViewModel.userRole(new UserRoleInterface(){
@Override
public void userRole(String role){
//Log.d(TAG, "onChanged: your user role: "+role);
}
});