簡體   English   中英

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

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

我需要在 Android Java 中的 onSuccess 方法之外獲取 userRole。如何獲取? 我嘗試實現接口和回調 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"); } });

您可以使用兩個選項。 第一個是使用 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;
}

然后在你的活動/片段中

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);
}

然后將接口設置為方法/函數的參數

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"));
 }
});

然后在您的活動/片段中

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