我正在使用Volley在我的应用程序中进行网络调用...对于许多屏幕...(比如片段)我正在做各种请求,如LoginRequest,FetchUsers Request,FetchExams Request .....以及处理响应和错误在每个片段中。
我可以使用的最佳方法是什么...... 1.子请求 2.创建接口/回调 3.在我的片段中获得结果/响应或错误响应......
这就是我在做的......创造了许多这样的方法......
private void syncAllUsers() {
progressDialog.setMessage("Loading Users...");
StringRequest jsonProductCategoryFetchRequest = new StringRequest(Request.Method.POST, Config.SELECT_USERS,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
if(Constants.DEBUG_MODE_ON)
Log.d(Constants.DEBUG_LOG, "RESPONSE for Teachers: "+response);
JSONObject result = new JSONObject(response);
boolean code = result.getBoolean("error");
if (!code) {
//Get the Users Json Array
JSONArray ja = result.getJSONArray("users");
if(ja != null) {
db.deleteAllUsers();
for (int i = 0; i < ja.length(); i++) {
JSONObject jobj = ja.getJSONObject(i);
User user = new User();
user.setId(jobj.getInt(User.KEY_ID));
user.setName(jobj.getString(User.KEY_NAME));
user.setEmail(jobj.getString(User.KEY_EMAIL));
user.setPhone(jobj.getString(User.KEY_PHONE));
user.setGender(jobj.getString(User.KEY_GENDER));
user.setUsername(jobj.getString(User.KEY_USERNAME));
user.setPassword(jobj.getString(User.KEY_PASSWORD));
user.setOrganization_id(jobj.getString(User.KEY_ORGANIZATION_ID));
user.setDob(jobj.getString(User.KEY_DOB));
user.setStatus(jobj.getString(User.KEY_STATUS));
user.setApi_key(jobj.getString(User.KEY_API_KEY));
user.setDate_created(jobj.getString(User.KEY_DATE_CREATED));
user.setRole_id(jobj.getInt(User.KEY_ROLE_ID));
//Delete local Teachers before updating
db.createUser(user);
} // for loop ends
}
}
//syncAllExams();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
} catch (Exception e) {
Log.d(Constants.DEBUG_LOG, "Exception Syncing Users: " , e);
Toast.makeText(getActivity(),"Something went wrong while fetching users", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
}
}
} , new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if(Constants.DEBUG_MODE_ON)
Log.d(Constants.DEBUG_LOG, "Error Response for Users : "+error.getCause()+""+error.toString());
Toast.makeText(getActivity(), getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
getActivity().finish();
startActivity(new Intent(getActivity(), MainActivity.class));
}
}) {
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put(User.KEY_ORGANIZATION_ID, preferencesManager.getOrganizationID());
params.put(User.KEY_API_KEY, preferencesManager.getApiKey());
Log.d("Registration", "PARAMS : " + params.entrySet());
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
// params.put("Content-Type", "application/json; charset=utf-8");
params.put("Content-Type", "application/x-www-form-urlencoded");
String auth = preferencesManager.getApiKey();
params.put("Authorization", auth);
return params;
}
};
MyApplication.getInstance().addToReqQueue(jsonProductCategoryFetchRequest);
}
我认为会有一种干净的方式来执行此操作。任何建议。
答案 0 :(得分:1)
我一直在使用这个类创建请求,它使用gson自动将你的json转换为你的对象。在这里找到示例: https://gist.github.com/ficusk/5474673
答案 1 :(得分:1)
创建请求管理器..这只涉及请求您的Web服务。该Manager还应该处理任何网络错误和其他非应用程序层的错误。
在您的业务逻辑所在的Model类中使用此请求管理器。发送请求参数为JSON ..您也可以将不同的侦听器发送到请求管理器,这样当Web服务响应出现时,它会直接传递给您Model类,您可以根据需要解析JSON响应。
这样解析逻辑保留在Model类中,Requesting逻辑保留在Request Manager中。所以将来如果你改变web服务地址,你只需要检查一个地方..如果你改变了webservice的请求和响应参数,你就不要需要更改请求管理器,只需更改Model类...
可能还有其他一些方法......
public final class RequestManager {
private static final String ROOT_HOST = //Your Webservice Host Root.
private RequestQueue queue;
public RequestManager(final Context context) {
queue = Volley.newRequestQueue(context);
}
//Internal Calling method .. Not exposed..
private void doRequest(final int method, final String url, final JSONObject jsonParam, final Response.Listener<JSONObject> listener,
final Response.ErrorListener errlsn) {
JSONObjectRequest jsonObjectRequest = new SONObjectRequest(method, url, jsonParam, listener, errlsn);
queue.add(jsonObjectRequest);
}
public void doLogin(final User user, final Response.Listener<JSONObject> listener, final Response.ErrorListener errlsn)
throws Exception {
// Make login request JSON here
if (user == null || listener == null || errlsn == null) {
//throw Exception
}
final JSONObject jsonObj = new JSONObject();
//Convert user object to JSON Object
doRequest(Request.Method.GET, LOGIN_URL, jsonObj, listener, errlsn);
}
}