我想发送一个新的JsonObjectRequest
请求(GET)
下面是我的代码:
final VolleyApplication volleyApplication = VolleyApplication.getInstance();
volleyApplication.init(getApplicationContext());
JsonArrayRequest req = new JsonArrayRequest("http://localhost:8080/webapi/", new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
try {
VolleyLog.v("Response:%n %s", response.toString(4));
System.out.print(response.toString());
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
Type listType = new TypeToken<List<MyEntity>>() {
}.getType();
myList = gson.fromJson(response.toString(), listType);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.e("Error: ", error.getMessage());
System.out.print(error.getMessage());
}
}
);
RequestQueue requestQueue = volleyApplication.getRequestQueue();
requestQueue.add(req);
这在CCD_ 2上起作用,并列出一些对象,但它不起作用。正如我在调试模式中看到的,这个方法的进程工作了两次。在第一次处于RequestQueue requestQueue = volleyApplication.getRequestQueue(); requestQueue.add(req);
时。。。。线它跳到方法的末尾。但它可以工作,并且第二次获得数据。这把我的代码搞砸了。
还有我在下面的VolleyApplication课程
public final class VolleyApplication {
private static VolleyApplication instance = null;
public static final VolleyApplication getInstance() {
if (instance == null) {
instance = new VolleyApplication();
}
return instance;
}
private RequestQueue requestQueue;
private ImageLoader imageLoader;
private boolean initialized = false;
private VolleyApplication() {
}
public void init(final Context context) {
if (initialized) {
return;
}
requestQueue = Volley.newRequestQueue(context);
int memory = ((ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE)).getMemoryClass();
int cacheSize = 1024 * 1024 * memory / 8;
// imageLoader = new ImageLoader(requestQueue, new BitmapLruCache(cacheSize));
}
public RequestQueue getRequestQueue() {
if (requestQueue == null) {
throw new RuntimeException("Init first");
}
return requestQueue;
}
public ImageLoader getImageLoader() {
if (imageLoader == null) {
throw new RuntimeException("Init first");
}
return imageLoader;
}
}
@seradd
你把它解释错了。
它实际上只执行了一次。您在调试模式中看到的是,
第一次创建requestObject
并将其添加到RequestQueue
。RequestQueue
然后执行它,一旦它将从URL获得响应,它将分别从Response.Listener
和Response.ErrorListener
接口执行其回调函数onResponse()
和onErrorResponse()
。
所以我建议你,无论你在添加任务后正在做什么任务到RequestQueue调用,将该代码添加到
onResponse()
方法