我重構了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