Reputation: 970
I use Volley in my application for request and response . the problem is i should call following line to get request through volley and the difference between these line is just the type of object witch jsonArray
should cast to(like NewsItem) second problem is showing object's value in the xml layout after get response. is there any way to summarize these lines in one method and call this method fore different object types?
private void GetOnlineNewsContent() {
CacheRequest cacheRequest = new CacheRequest(ContentActivity.this,Request.Method.POST,
service_address,
new Response.Listener<NetworkResponse>() {
@TargetApi(Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(NetworkResponse response) {
try {
final String jsonString = new String(response.data,
HttpHeaderParser.parseCharset(response.headers));
JSONArray jsonArray = new JSONArray(jsonString);
newsItem = NewsItem.fromJson(jsonArray.getJSONObject(0), term_id);
ShowContent(newsItem);
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
pDialog.hide();
}
});
Upvotes: 0
Views: 715
Reputation: 2633
Yes. You should look at and learn Generics
in Java.
You would need to make this new method to receive generic type, and then perform the operation on particular type of the class.
For that, your newItem
and other 3 classes should come from common base class.
Basic tutorial on generics can be found here, https://docs.oracle.com/javase/tutorial/java/generics/
Upvotes: 1