这是一个简单的项目,我正在使用Volley从https://jsonplaceholder.typicode.com/todos/1获取json数据(作为字符串)
我将Activity,Logic(使用Presenter)和Service(将与其余服务进行对话,使用POST,GET方法等)分开。
现在,在活动中,有一个登录按钮及其单击侦听器(其实现在WelcomePresenter中)
当用户输入电子邮件和密码时(不要将自己与电子邮件混淆,这只是将来的功能),我在服务类中合并了字符串“ https://jsonplaceholder.typicode.com/todos/”和用户密码,并执行GET方法
如果响应http状态码为200,则我正在打开新的活动,该活动将打印公正的响应,否则保持相同的活动并使吐司消息“填充区域”
在这里发生了什么事
这是WelcomeView
public class WelcomeActivity extends AppCompatActivity implements WelcomeView {
private WelcomePresenter welcomeBasePresenter;
private EditText usermail, userpassword;
private Button loginButton;
private RequestQueue requestQueue;
private Service restService;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
this.usermail = findViewById(R.id.welcome_activity_edittext_username);
this.userpassword = findViewById(R.id.welcome_activity_edittext_userpassword);
this.loginButton = findViewById(R.id.welcome_activity_button_login);
this.requestQueue = VolleySingleton.getInstance(this).getRequestQueue();
this.restService = new ServiceImpl(this.requestQueue);
this.welcomeBasePresenter = new WelcomePresenterImpl(this, this.restService);
this.loginButton.setOnClickListener((v) -> {
String usermail = this.usermail.getText().toString();
String password = this.userpassword.getText().toString();
this.welcomeBasePresenter.loginButtonListener(usermail, password);
});
}
public void loadErrorMessage(String... errorMessage) {
//make toast message
}
public void loadUserPageActivity() {
// load new activity
}
}
这是WelcomePresenter
public class WelcomePresenterImpl implements WelcomePresenter {
private WelcomeView welcomeView;
private Service service;
public WelcomePresenterImpl(WelcomeView responsibleView, Service restServis){
this.welcomeView = responsibleView;
this.service = restServis;
}
public void loginButtonListener(String usermail, String userpassword) {
service.validateUser(usermail, userpassword);
if (service.getUserRegisterHttpCode() == 200){
this.welcomeView.loadUserPageActivity(service.getJsonData());
}else{
this.welcomeView.loadErrorMessage();
}
}
}
这是与后端对话的Service类
public class ServiceImpl implements Service{
private String jsonData;
private RequestQueue requestQueue;
private int userRegisterHttpCode;
public ServiceImpl(RequestQueue requestQueue){
this.requestQueue = requestQueue;
}
public void validateUser(String usermail, String userpassword){
String url = EndPoint.URL.getUrl() + userpassword;
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
url,
response -> userToken = response,
error -> setUserRegisterHttpCode(error.networkResponse.statusCode)){
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
setUserRegisterHttpCode(response.statusCode);
return super.parseNetworkResponse(response);
};
this.requestQueue.add(stringRequest);
}
}