【发布时间】:2015-08-29 12:01:33
【问题描述】:
我正在使用 Volley 从服务器获取数据。我有 2 个活动,活动 A 和 B。两者都通过单例使用 Volley 和相同的请求队列来获取数据。在活动 A 中一切正常,当我开始活动 B 时,我得到了 Volley 的响应。
问题是,如果我从活动 B 完成并移动到 A,然后再次开始 B,Volley 似乎无法得到响应。我做错了什么?
我的单身
public class CustomVolleyRequestQueue {
private static CustomVolleyRequestQueue mInstance;
private static Context mCtx;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private CustomVolleyRequestQueue(Context context) {
mCtx = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(
LruBitmapCache.getCacheSize(mCtx)));
}
public static synchronized CustomVolleyRequestQueue getInstance(Context context) {
if (mInstance == null) {
mInstance = new CustomVolleyRequestQueue(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
Cache cache = new DiskBasedCache(mCtx.getCacheDir(), 10 * 1024 * 1024);
Network network = new BasicNetwork(new HurlStack());
mRequestQueue = new RequestQueue(cache, network);
// Don't forget to start the volley request queue
mRequestQueue.start();
}
return mRequestQueue;
}
public ImageLoader getmImageLoader(){
return mImageLoader;
}
}
我的自定义请求
public class CustomJSONObjectRequest extends JsonObjectRequest{
private Priority mPriority;
public CustomJSONObjectRequest(int method, String url, JSONObject jsonRequest,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, jsonRequest, listener, errorListener);
//this.setShouldCache(true);
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
@Override
public RetryPolicy getRetryPolicy() {
// here you can write a custom retry policy
return super.getRetryPolicy();
}
public void setPriority(Priority priority) {
mPriority = priority;
}
@Override
public Priority getPriority() {
return mPriority == null ? Priority.NORMAL : mPriority;
}
}
我在我的 Activity B 的 onStart 上执行并添加请求,如下所示,
protected void onStart() {
super.onStart();
mQueue = CustomVolleyRequestQueue.getInstance(this.getApplicationContext())
.getRequestQueue();
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
jsonRequest.setPriority(Request.Priority.HIGH);
mQueue.add(jsonRequest);
setupRecyclerView(rv, rv2, rv3);
}
我的活动 B 实现了响应侦听器,我在其中简单地解析 JSON 并在 UI 上显示数据。
我已经讨论这个问题很长一段时间了,我已经了解了 Volley 其他功能的提示和技巧,缓存,忽略请求,深入使用库并将其与其他库一起使用.然而,我仍然看不到我在这里做错了什么。
【问题讨论】:
-
您是否尝试将其放入
onResume或onPostResume中? -
@BNK 不,我知道我哪里出错了,但是谢谢,我会尝试的。
标签: android json web-services android-volley