简体   繁体   English

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

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

I need to get the userRole outside the onSuccess method in Android Java. How to get that?我需要在 Android Java 中的 onSuccess 方法之外获取 userRole。如何获取? I tried implementing interface and callback function and that also not worked.我尝试实现接口和回调 function,但也没有用。

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

There are two options you can use.您可以使用两个选项。 The first one is using Mutablelivedata and the second is using an Interface.第一个是使用 Mutablelivedata,第二个是使用接口。 Assuming you are using MVVM pattern.假设您正在使用 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;
}

then in your activity/fragment然后在你的活动/片段中

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

The second is making an interface callback二是进行接口回调

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

Then set the interface as a parameter on your 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"));
 }
});

Then in your Activity/Fragment然后在您的活动/片段中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM