【发布时间】:2017-06-04 10:58:09
【问题描述】:
这是一种返回自定义列表的方法。但是我正在更新异步任务(OnResponse)中的列表。我不得不使用嵌套的凌空请求。我已经声明了一个列表项,但无法在 OnRespose 方法中使用它。谁能帮我这个?如何从方法中返回列表项。
private ArrayList<sItem> fetchApiData(){
ArrayList<sItem> list= new ArrayList<>();
String url="http://www.gadgetsinnepal.com.np/wp-json/wp/v2/posts/";
JsonArrayRequest jsArrayRequest = new JsonArrayRequest
(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
sItem sitem=new sItem();
JSONObject item = (JSONObject) response
.get(i);
String id = item.getString("id");
sitem.id=id;
String date = item.getString("date");
JSONObject titleobj = item
.getJSONObject("title");
String title= titleobj.getString("rendered");
sitem.title=title;
String featuredMedia= item.getString("featured_media");
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
"http://www.gadgetsinnepal.com/wp-json/wp/v2/media/"+featuredMedia, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject nested_response) {
try {
JSONObject guilld = nested_response.getJSONObject("guid");
String featured_img_url = guilld.getString("rendered");
sitem.img=featured_img_url;
list.add(sitem);
//Toast.makeText(getApplicationContext(),"IMAGE :" + list.get(0),Toast.LENGTH_LONG).show();
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),
"ERROR "+error.getMessage(), Toast.LENGTH_LONG).show();
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(),"network timeout error",
Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
//TODO
} else if (error instanceof ServerError) {
//TODO
} else if (error instanceof NetworkError) {
//TODO
} else if (error instanceof ParseError) {
//TODO
}
}
});
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(
7000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsonObjReq);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});
MySingleton.getInstance(getApplicationContext()).addToRequestQueue(jsArrayRequest);
return list;
}
【问题讨论】:
标签: java android android-asynctask android-volley