我重构了checkLogin()
,它生活在LoginActivity
类中,但我仍然认为它可以被重构得更好。试图更好地重构
private void checkLogin(final String email, final String password) {
// Tag used to cancel the request
String tag_string_req = "req_login";
pDialog.setMessage("Logging in ...");
showDialog();
LoginRequest loginRequest = new LoginRequest(Request.Method.POST, AppConfig.getUrlLogin(), ReqSuccessListener(), ReqErrorListener()) {
protected Map<String, String> getParams() {
// Posting parameters to login url
Map<String, String> params = new HashMap<String, String>();
params.put("email", email);
params.put("password", password);
return params;
}
};
// Adding request to request queue
AppController.getInstance().addToRequestQueue(loginRequest, tag_string_req);
}
的ReqSuccessListener()
和ReqErrorListener()
的实施也住在LoginActivity
类。看起来像这样:
private Response.Listener<String> ReqSuccessListener() {
return new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Login Response: " + response.toString());
hideDialog();
try {
session.setLogin(true);
JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String uid = user.getString("id");
String name = user.getString("name");
String email = user.getString("email");
// Inserting row in users table
db.addUser(name, email, uid);
// Launch main activity
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
} catch (JSONException e) {
// JSON error
Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
};
}
private Response.ErrorListener ReqErrorListener() {
return new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
int statusCode = error.networkResponse.statusCode;
NetworkResponse response = error.networkResponse;
Log.d("testerror", "" + statusCode + " " + new String(response.data));
if (statusCode != 200) {
Toast.makeText(getApplicationContext(), new String(response.data), Toast.LENGTH_LONG).show();
hideDialog();
}
}
};
}
我的问题很简单,我该如何重构这更好?或者我已经重构了足够好的?
另外这里是我的链接,向您展示代码在重构前后的外观。这里是链接,如果你想看到它:https://github.com/superzaky/Kenzup/compare/3b30426bc02873607806525d62d2744921481cd5...command-loginrequest
因此,左侧是重构前的代码,右侧是重构后的代码。
“更好”是什么意思?这似乎是一个相当主观的问题。 – Brucelet
好了,在'LoginRequest'或其他地方放置'ReqSuccessListener()'和'ReqErrorListener()'的实现。 – superkytoz