我使用Volley库来加载图像并要求从休息api的结果,图书馆工作正常,我正在做一些懒惰的好工作,但有时和随机(我无法检测到原因)应用程序不会在用户发出请求后刷新结果。Android Volley发送请求没有发送到服务器,并没有刷新
我创建的应用程序显示了多种语言的新闻流,当我将用户语言从ENGLiSH更改为FRENCH时,我重建了我的json请求并将其发送给服务器,但我惊讶地看到响应包含英文文本,我在另一个Rest Tool(铬扩展名)中使用相同的请求,并且响应将FRENCH文本发回!有趣的是不是。
我已经登录到服务器,我监视了日志,我惊讶地发现我的所有请求都没有到达我的服务器,并且日志显示旧值,我对自己说,也许我的网络没有Android设备,所以我已经删除了应用程序,并重新安装它,日志文件开始与我的手机请求跳舞..所以该设备有互联网连接,它正确地调用服务器..
所以我想也许有一些tweeking需要Volley配置不需要缓存时不需要,下面的示例代码来自我的应用程序:
VolleyHelper.java
import android.content.Context;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
//import com.github.volley.example.toolbox.BitmapLruCache;
/**
* Helper class that is used to provide references to initialized RequestQueue(s) and ImageLoader(s)
*/
public class VolleyHelper {
private static final int MAX_IMAGE_CACHE_ENTIRES = 100;
private static RequestQueue mRequestQueue;
private static ImageLoader mImageLoader;
private VolleyHelper() {
}
public static void init(Context context) {
mRequestQueue = Volley.newRequestQueue(context);
mImageLoader = new ImageLoader(mRequestQueue, new BitmapLruCache(MAX_IMAGE_CACHE_ENTIRES));
}
public static RequestQueue getRequestQueue() {
if (mRequestQueue != null) {
return mRequestQueue;
} else {
throw new IllegalStateException("RequestQueue not initialized");
}
}
/**
* Returns instance of ImageLoader initialized with {@see FakeImageCache} which effectively means
* that no memory caching is used. This is useful for images that you know that will be show
* only once.
*/
public static ImageLoader getImageLoader() {
if (mImageLoader != null) {
return mImageLoader;
} else {
throw new IllegalStateException("ImageLoader not initialized");
}
}
}
AppController.java
import android.app.Application;
import android.text.TextUtils;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
public class AppController extends Application {
public static final String TAG = AppController.class
.getSimpleName();
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static AppController mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized AppController getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public ImageLoader getImageLoader() {
getRequestQueue();
if (mImageLoader == null) {
mImageLoader = new ImageLoader(this.mRequestQueue,
new LruBitmapCache());
}
return this.mImageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
// set the default tag if tag is empty
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
JSONParser.java
import java.io.InputStream;
import java.util.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
Log.e("MakeHttpRequest : ", "--MakeHttpRequest---");
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我的要求从MainActivity.java
从我的新闻适配器AppController p = AppController.getInstance();
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("sectionId", C.ART); // section of news
params.put("pageNumber", 0); // page number
params.put("numberOfRecords", 10); // number of records we want to retrieve
toggleLoader(isRefresh);
JsonObjectRequest req = new JsonObjectRequest(C.SERVER_URL + C.getNews,
new JSONObject(params), new Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
String Array = response.toString();
adapter.refreshAdapter(getRowList(Array), isRefresh);
// setRefreshActionButtonState(false);
loadingMore = false;
isRefresh = false;
toggleLoader(isRefresh);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
// hideProgressDialog();
Toast.makeText(getBaseContext(),
"Error while getting Data", Toast.LENGTH_SHORT)
.show();
}
});
// Adding request to request queue
p.addToRequestQueue(req, tag_json_arry);
RefreshAdapter方法:
public synchronized void refreshAdapter(List<NewsModel> dataitems, boolean isRefresh) {
if(isRefresh)
items.clear();
items.addAll(dataitems);
notifyDataSetChanged();
}
任何帮助或想法,欢迎。