java - 在另一个片段中使用 Firestore 回调
问题描述
我正在尝试将我的代码分成类似 MVC 的部分。我有一个片段,我想在其中显示从 Firestore 获取的用户名。我还有一个类(HomeController),我在其中放置了逻辑。在这个类中,我尝试实现一个从文档中获取用户名的方法。
家庭控制器
public void getWelcomeNameText(final getNameCallback callback) {
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
welcomeName = document.getString("clientName");
}
}
callback.onCallback(welcomeName);
}
});
}
我正在使用接口进行回调。
public interface getNameCallback {
void onCallback(String name);
}
同样在构造函数中,我调用了上面的方法。
public HomeController() {
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
userID = fAuth.getUid();
docRef = fStore.collection("Clients").document(userID);
activeJobRef = fStore.collection("ActiveJobs");
getWelcomeNameText(new getNameCallback() {
@Override
public void onCallback(String name) {
welcomeName = name;
//I want to pass this welcomeName to HomeFragment
}
});
}
这完美地获取了用户名,但我想在我的名为 HomeFragment 的片段中使用此方法来设置 TextView 的文本。所以实际上我想传递welcomeName变量。但实际上我不知道该怎么做。我在 Fragment 中实现了getNameCallback。
首页片段
public class HomeFragment extends Fragment implements HomeController.getNameCallback, View.OnClickListener {
//variables
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
getActivity().getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
View view = inflater.inflate(R.layout.fragment_home, container, false);
postJob = view.findViewById(R.id.button_add_job);
logout = view.findViewById(R.id.button_sign_out);
bottomNav = getActivity().findViewById(R.id.bottom_nav);
bottomNav.setVisibility(View.VISIBLE);
loginName = view.findViewById(R.id.textView_login_name);
noDataText = view.findViewById(R.id.textView_no_active_job);
homeController = new HomeController();
//here I want something like: loginName.setText(userNameFromCallback);
return view;
}
@Override
public void onCallback(String name) {
//maybe I have to do something here?
}
感谢您阅读本文——可能是一个非常业余的问题!
解决方案
得到了解决方案,我知道这是一个菜鸟问题:) 我刚打电话:
homeController.getWelcomeNameText(new HomeController.getNameCallback() {
@Override
public void onCallback(String name) {
loginName.setText(name);
}
});
推荐阅读
- python - Python ValueError: no enough values to unpack (expected 3, got 1)
- java - 如何使用 moshi、retrofit 和 java 处理包装数据?
- java - 如何在 Apache POI 中部分加粗段落?(Word 文档)
- c++ - 将字符串隐式转换为 string_view
- asp.net - 会话登录 - 会话字符串为空
- javascript - JavaScript 声明或声明 expected.ts(1128)
- list - Python 3.7:为什么只打印列表中的最后一项?
- javascript - 复选框的多选在 JQuery 中不起作用
- c++ - 参数类型“WCHAR *”与类型“const char *”的参数不兼容
- java - ANTLR / java / SDK 生成-编译-执行序列在 Windows10 命令窗口上失败