为什么我的活动没有看到观察到的物体变化? [英] Why does my activity doesn't see an observed object change?

查看:64
本文介绍了为什么我的活动没有看到观察到的物体变化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android开发的新手,我正在尝试了解MVVM架构的实时数据. 我试图使主要活动在属于该活动的视图模型的对象中发生更改时得以识别.

I'm new to Android development and i am trying to understand Live Data with MVVM architecture. I am trying to make the main activity recognize when there is a change in an object that belong to the view-model of the activity.

我创建了一个简单的登录活动,该活动从用户名和密码字段获取文本,并将其传递给视图模型的登录功能,然后该功能将数据发送到用户存储库,然后向Spring发出POST请求-在我的PC上运行的服务器. 如果用户名和密码正确,则存储库登录函数将返回具有已登录用户名的MutableLiveData对象,否则返回null. 存储库工作正常(从服务器返回的数据正确).视图模型的字段类型为MutableLiveData,在调用登录函数后需要对其进行更新.在活动中,应该有一个观察者,该事件应在loginInUser字段(MutableLiveData类型)字段中发生更改时得到通知,即使发生更改,也永远不会激活该观察者的onChange函数.

I have created a simple login activity that takes the text from the username and password fields and passes them to the view-model's login function, then the function sends the data to the users repository and then it makes a POST request toa spring-server that is running on my PC. The repository login function returns a MutableLiveData object with the logged-in username if the username and password are right, and null as it's value otherwise. The repository works fine( the data coming back from the server is correct). The view-model has a field of type MutableLiveData and it is need to be updated after the login function is called. In the activity there is an observer that supposed to be notified when a changed accrued in the loggedInUser field (of type MutableLiveData) field and even though there is a change, the function onChange of the observer is never activated.

我希望有一些代码可以帮助我更好地解释.

There is some code that i hope will help me explain better.

主要活动:

public class MainActivity extends AppCompatActivity {
        public EditText usernameTxt;
        public EditText passwordTxt;
        public Button loginBtn;
        public String loggedInuUser;
        LoginViewModel loginViewModel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {



        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        usernameTxt = findViewById(R.id.usernameTxt);
        passwordTxt   = findViewById(R.id.passwordTxt);
        loginBtn   = findViewById(R.id.loginBtn);

        loginViewModel = ViewModelProviders.of(this ).get(LoginViewModel.class);
        loginViewModel.init();
        try {
            loginViewModel.getLoggedInUser().observe(this, new Observer<String>() {
                        @Override
                        public void onChanged(@Nullable String s) {
                            Toast toast=  Toast.makeText(MainActivity.this,"changed" , Toast.LENGTH_LONG );
                            toast.show();
                        }
                    }
            );
        }catch (Exception e){
            System.out.println("==========================================================");
            System.out.println( e.getMessage());
            System.out.println("==========================================================");
        }

    }


    protected void onLogInCliked(View v ){

//        Toast toast=  Toast.makeText(getApplicationContext(),loggedInuUser, Toast.LENGTH_LONG );
//        toast.show();
        loginViewModel.login(usernameTxt.getText().toString(),passwordTxt.getText().toString());
//        Toast toast2=  Toast.makeText(getApplicationContext(),loggedInuUser, Toast.LENGTH_LONG );
//        toast2.show();


    }
}

视图模型:

public class LoginViewModel extends ViewModel {


    private UsersRepository usersRepository;
    private MutableLiveData<String> loggedInUser;

    public void init(){
        if(loggedInUser!= null){
            return;
        }

        usersRepository = UsersRepository.getInstance();
        loggedInUser=new MutableLiveData<>();
    }


    public MutableLiveData<String> getLoggedInUser(){
        return loggedInUser;
    }

    public void login(String userName , String hashedPassword) {

        loggedInUser = usersRepository.login(userName, hashedPassword);
    }
}

存储库:

public class UsersRepository {

private static UsersRepository usersRepository;

public static UsersRepository getInstance(){
    if (usersRepository == null){
        usersRepository = new UsersRepository();
    }
    return usersRepository;
}

private UsersRepositoryApi usersRepositoryApi;

public UsersRepository(){
    usersRepositoryApi = RetrofitService.cteateService(UsersRepositoryApi.class);
}


public MutableLiveData<String> login(String username , String hashedPassword){
   final MutableLiveData<String> loggedInUser = new MutableLiveData<>();
    User user = new User(username,hashedPassword);

    usersRepositoryApi.login(user).enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) {
                loggedInUser.setValue(response.body());
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            loggedInUser.setValue(null);
        }
    });

    return loggedInUser;
}

}

在mainActivity中,我设置了观察者,并希望该应用显示我的Toast消息,但什么也没发生.

In the mainActivity i set the observer and i expect the app to show my the Toast message but nothing happens.

我试图查看视图模型中发生了什么,这有点奇怪, 所以我打印了这样的东西:

i have tried to see what happens in the view-model and it is a little strange, so i printed stuff like this:

    public void login(String userName , String hashedPassword) {

    System.out.println("222======================================");
    System.out.println("==========================================");
    System.out.println("==========================================");
    System.out.println(loggedInUser.getValue());
    System.out.println("==========================================");
    System.out.println("==========================================");
    System.out.println("==========================================");
    loggedInUser = usersRepository.login(userName, hashedPassword);

    System.out.println("333======================================");
    System.out.println("==========================================");
    System.out.println("==========================================");
    System.out.println(loggedInUser.getValue());
    System.out.println("==========================================");
    System.out.println("==========================================");
    System.out.println("==========================================");

}

第一次运行登录功能时,222和333的输出均为空,但是第二次运行登录功能时,222的输出为loggingInUser,333的输出为空

in first time that i run the login function the output of both 222 and 333 was null, but in the second time i run the login function the output of 222 was the loggedInUser and the output of 333 was null

在两种情况下都未观察到观察者的on change功能

in both cases the on change function of the observer was unvisited

有人知道我在做什么错吗?

does anyone have any idea of what i am doing wrong??

谢谢你 罗宁!

推荐答案

这里的问题是存储库中的存储库代码,您正在创建可变实时数据的新对象并观察不同的对象.

here your problem is with repository code inside repository you are creating new object of mutable live data and observing different one.

Interface Callback{
    onSuccess(String response)
    onError(String error)
}

public void login(String username , String hashedPassword,Callback callback){
    final MutableLiveData<String> loggedInUser = new MutableLiveData<>();
    User user = new User(username,hashedPassword);

    usersRepositoryApi.login(user).enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            if (response.isSuccessful()) {
                callback.onSuccess(response.body());
            }
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            callback.onError(null);
        }
    });
}

//login method of your viewmodel 
public void login(String userName , String hashedPassword) {
     usersRepository.login(userName, hashedPassword,new Callback(){
          void onSuccess(String responsebody){
               loggedInUser.setValue(responsebody);
          }

          void onError(String error){
               loggedInUser.setValue(responsebody);
          }
     });
}

这篇关于为什么我的活动没有看到观察到的物体变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆