简体   繁体   English

Android MVVM 存储库和 ViewModel 问题

[英]Android MVVM Repository and ViewModel Question

I have just start my MVVM pattern.我刚刚开始我的 MVVM 模式。 And when I do the login, I have some problems.当我登录时,我遇到了一些问题。 Here is my code.这是我的代码。

1. login service 1.登录服务

public interface LoginService {
    @FormUrlEncoded
    @POST("user/login")
    Call<JsonObject> validateLogin(@Field("phoneNum") String phoneNum, @Field("password") String password);
}

2. Repository 2. 存储库

public class LoginRepository {
    private static final String TAG = "LoginRepository";
    private static LoginRepository instance;

    public static LoginRepository getInstance() {
        if (instance == null) {
            instance = new LoginRepository();
        }
        return instance;
    }

    public MutableLiveData<JsonObject> getLoginMessage(String phoneNum, String password) {
        final MutableLiveData<JsonObject> message = new MutableLiveData<>();
        LoginService service = RetrofitClass.getLoginService();
        Call<JsonObject> call = service.validateLogin(phoneNum, password);
        call.enqueue(new Callback<JsonObject>() {
            @Override
            public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
                if (response.isSuccessful()) {
                    JsonObject info = response.body();
                    message.setValue(info);
                }
            }

            @Override
            public void onFailure(Call<JsonObject> call, Throwable t) {
                Log.d(TAG, "fail!");
                message.setValue(null);
            }
        });
        return message;
    }
}

3. viewmodel 3.视图模型

the method queryRepo is to request login service using phoneNum and password. queryRepo方法是使用 phoneNum 和密码请求登录服务。 And it will be used when user click the login button.当用户单击登录按钮时将使用它。

public class LoginViewModel extends ViewModel {
    private static final String TAG = "UserProfileViewModel";

    private LoginRepository mLoginRepository;

    private MutableLiveData<JsonObject> message = new MutableLiveData<>();

    public void queryRepo(String phoneNum, String password) {
        this.message = mLoginRepository.getLoginMessage(phoneNum, password);
    }

    public LiveData<JsonObject> getMessage() {
        return message;
    }
}

4. Activity login 4.活动登录

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "LoginActivity";

    private TextView mForgetPswTv, mRegisterTv;
    private EditText mPhoneEdt, mPasswordEdt;
    private QMUIRoundButton mLoginBtn;
    private ProgressBar mProgressBar;

    private LoginViewModel mLoginViewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getSupportActionBar().hide();
        setContentView(R.layout.activity_login);
        initView();
        bindOperation();
        mLoginViewModel = new ViewModelProvider(this).get(LoginViewModel.class);
        mLoginViewModel.getMessage().observe(this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mPasswordEdt.setText(jsonObject.toString());
                } else Log.d(TAG, "null");
            }
        });


    }


    private void initView() {
        mProgressBar = (ProgressBar) findViewById(R.id.progress_circular_movie_article);
        mForgetPswTv = findViewById(R.id.forget_psw_tv);//忘记密码
        mRegisterTv = findViewById(R.id.register_tv);//立即注册
        mLoginBtn = findViewById(R.id.login_btn);
        mPhoneEdt = findViewById(R.id.phone_edt);
        mPasswordEdt = findViewById(R.id.password_edt);
    }


    private void bindOperation() {
        mForgetPswTv.setOnClickListener(LoginActivity.this);
        mRegisterTv.setOnClickListener(LoginActivity.this);
        mLoginBtn.setOnClickListener(v -> {
            mLoginViewModel.queryRepo(mPhoneEdt.getText().toString(), mPasswordEdt.getText().toString());
        });
    }


}

I think it's clear, but I really don't know why it doesn't work, When I touch the login button, this.message.getValue() will change to null.我认为很清楚,但我真的不知道为什么它不起作用,当我触摸登录按钮时, this.message.getValue()将更改为 null。 is there something important that I missed?我错过了什么重要的事情吗? actually, if I don't initialize the message, the first time I call queryRepo is fine, but once the message is assigned a value, if I call queryRepo again, message.getValue() will be null.实际上,如果我不初始化消息,我第一次调用 queryRepo 就可以了,但是一旦为消息分配了一个值,如果我再次调用 queryRepo,message.getValue() 将是 null。

I finally made it, just as below.我终于成功了,如下图。

mLoginBtn.setOnClickListener(v -> {
    mLoginViewModel.queryRepo(mPhoneEdt.getText().toString(), mPasswordEdt.getText().toString());
    mLoginViewModel.getMessage().observe(this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mPasswordEdt.setText(jsonObject.toString());
                } else Log.d(TAG, "null");
            }
        });
});

Thanks for everybody again!再次感谢大家!

Try to Observe live data into Button OnClickListener, Like this, and check尝试将实时数据观察到 Button OnClickListener 中,像这样,并检查

 mLoginBtn.setOnClickListener(v -> {
            mLoginViewModel.queryRepo(mPhoneEdt.getText().toString(), mPasswordEdt.getText().toString());

            mLoginViewModel.getMessage().observe(this, new Observer<JsonObject>() {
            @Override
            public void onChanged(JsonObject jsonObject) {
                if (jsonObject != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mPasswordEdt.setText(jsonObject.toString());
                } else Log.d(TAG, "null");
            }
       });
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何为MVVM模式链接Retrofit和Repository / ViewModel? - How to link Retrofit and Repository/ViewModel for a MVVM pattern? 在 Android 的 MVVM 中将 ViewModel State 保存在哪里? - Where to Save ViewModel State in Android's MVVM? 使用架构组件 MVVM 进行身份验证,将令牌从 Repository 传递到 ViewModel - Authentication with Architecture Components MVVM, passing token from Repository to ViewModel 是否将 hsahMap 传递到存储库 mvvm android - Is right pass hsahMap to repository mvvm android Android MVVM/Repository 如何强制 LiveData 从存储库更新? - Android MVVM/Repository how to force LiveData to update from repository? Viewmodel 无法创建类 Android Java MVVM 的实例 - Viewmodel cannot create an instance of class Android Java MVVM ViewModel 中的不可观察模型对象是针对 Android 中的 MVVM 架构吗? - Is non-observable model object in the ViewModel against MVVM architecture in Android? Android MVMVM-每个Crud操作都应该拥有自己的ViewModel吗? - Android mvvm - does every crud operation should have it own ViewModel? 如何使用 MVVM 架构上的 Room 在 android 存储库 class 中查询? - How to query inside android repository class using Room on MVVM architechture? 使用 java 在 android 中使用存储库实现 ViewModel 和 LiveData 的正确方法? - Correct way to implement ViewModel and LiveData with Repository in android using java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM