我正在使用 Live Data Architecture 实现数据绑定。我做了所有的事情,但我无法找到我必须在片段中更新响应值的地方。我做了一个按钮,然后单击按钮,我可以将数据发送到服务器并获得响应。但我的问题是片段中的味精值或成功值如何更新。当 value 为 update 时,我的观察者没有被调用。有什么我做错了执行。提前致谢。
我的片段
**Oncreate Method**
{ signUpViewModel=ViewModelProviders.of(getActivity()).get(SignUpViewModel.class);
observeViewModel(signUpViewModel);
return view;
}
//my observe class
private void observeViewModel(SignUpViewModel signinViewModel) {
if (signinViewModel.getmessage() != null) {
signinViewModel.getmessage().observe(this, new Observer<String>() {
@Override
public void onChanged(@Nullable String msg) {
if (msg != null) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
}
}
});
}
}
//button clicked
public void onSignUpClicked(View view)
{
signUpViewModel.registerUser(userFName, userLName, userEmail,userPassword);
}
SignUpViewModel.class
public class SignUpViewModel extends ViewModel{
private LoginFragmentRepository loginFragmentRepository;
private LiveData<String> sucessMsg;
String signUpMsg;
public void registerUser(String userFName, String userLName, String userEmail, String userPassword) {
loginFragmentRepository=new LoginFragmentRepository();
sucessMsg= loginFragmentRepository.registerUser( userFName, userLName, userEmail, userPassword);
}
/**
* get signup msg
* @return
*/
public LiveData<String> getmessage() {
return sucessMsg;
}
登录片段存储库
{
private ApiInterface apiInterface;
private UserDao userDao;
public LiveData<String> registerUser(String userFName, String userLName, String userEmail, String userPassword) {
apiInterface = RestApi.getRetroInstance().create(ApiInterface.class);
final MutableLiveData<String> msg = new MutableLiveData<>();
Call<SignUpModel> req = apiInterface.registerUser(userFName,userLName,userEmail,userPassword);
req.enqueue(new Callback<SignUpModel>() {
@Override
public void onResponse(Call<SignUpModel> call, Response<SignUpModel> response) {
if (response.isSuccessful()) {
//update this value in fragment
msg.postValue(response.body().getData());
//getReceipesListDataResponseMutableLiveData.setValue(NetworkResponse.success(receipes));
} else {
msg.postValue("Please check your network connection");
}
}
@Override
public void onFailure(Call<SignUpModel> call, Throwable t) {
msg.postValue("Please check your network connection");
}
});
return msg;
}
}