我试着把我的代码像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变量。但实际上我不知道怎么做。我在片段中实现了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?
}
感谢您阅读这个-可能是一个非常业余的-问题!
1条答案
按热度按时间gab6jxml1#
得到了答案,我知道这是一个愚蠢的问题:)我刚刚打电话: