Android MVVM存储库和ViewModel问题

时间:2020-08-18 01:22:24

标签: java android mvvm android-livedata

我刚刚开始我的MVVM模式。当我登录时,我遇到了一些问题。这是我的代码。

1。登录服务

from tkinter import *
import sqlite3

root = Tk()
root.geometry("400x400")
root.maxsize(400, 400)
root.title("Testing")

conn = sqlite3.connect(r'D:\Users\drmargis\Python Projects\Projects\GeNamenator\GeName_DB_2.db')
curs = conn.cursor()

curs.execute(""" SELECT * FROM themes """)
theme_list = curs.fetchone()
main_bg = theme_list[1]
button_bg = theme_list[2]
button_act_bg = theme_list[3]
frame_bg = theme_list[4]
text_color = theme_list[5]
entry_bg = theme_list[6]

root.configure(bg=main_bg)


def theme_green():
    main_bg = "#66cc99"
    button_bg = "#66cc00"
    button_act_bg = "#0b5345"
    frame_bg = "#66cc33"
    text_color = "#000000"
    entry_bg = "#ffffff"
    curs.execute(""" UPDATE themes SET main_bg=(?), button_bg=(?), button_act_bg=(?), frame_bg=(?), text_color=(?), entry_bg=(?) WHERE thm_id=1""",
                 (main_bg, button_bg, button_act_bg, frame_bg, text_color, entry_bg,))
    conn.commit()


def theme_red():
    main_bg = "#c2240b"
    button_bg = "#ae1f1f"
    button_act_bg = "#5d0909"
    frame_bg = "#c13323"
    text_color = "#000000"
    entry_bg = "#ffffff"
    curs.execute(""" UPDATE themes SET main_bg=(?), button_bg=(?), button_act_bg=(?), frame_bg=(?), text_color=(?), entry_bg=(?) WHERE thm_id=1""",
                 (main_bg, button_bg, button_act_bg, frame_bg, text_color, entry_bg,))
    conn.commit()


change_but = Button(root, font=("Calibri", 23, 'bold'), text="Change Green", fg=text_color, bg=button_bg, activebackground=button_act_bg, command=theme_green)
change_but.grid(row=0, column=0)
change_but = Button(root, font=("Calibri", 23, 'bold'), text="Change Red", fg=text_color, bg=button_bg, activebackground=button_act_bg, command=theme_red)
change_but.grid(row=1, column=0)

root.mainloop()

2。存储库

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

3。视图模型

方法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; } } 是使用phoneNum和密码请求登录服务的。当用户单击登录按钮时将使用它。

queryRepo

4。活动 login

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;
    }
}

我认为这很清楚,但是我真的不知道为什么它不起作用。当我触摸登录按钮时,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()); }); } } 将变为null。我错过了重要的事情吗? 实际上,如果我不初始化消息,则第一次调用queryRepo很好,但是一旦为消息分配了值,如果再次调用queryRepo,则message.getValue()将为null。

2 个答案:

答案 0 :(得分:1)

我终于做到了,如下。

joblib.load()

再次感谢大家!

答案 1 :(得分:0)

尝试像这样观察活动数据到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");
            }
       });
 });