Android Volley Post请求未发送到服务器且未刷新

时间:2014-11-25 09:56:04

标签: android caching android-volley

我正在使用Volley库加载图像并从rest api请求结果,库工作正常,我正在做一些懒惰的好工作,但有时和随机(我无法检测原因)在用户提出请求后,应用程序不会刷新结果。

我正在创建的应用程序以多种语言显示新闻流,当我将用户语言从ENGLiSH更改为FRENCH时,我会重建我的json请求并将其发送到服务器,但我很惊讶看到响应包含ENGLISH文本,我在另一个Rest Tool(chrome扩展名)中使用相同的请求,响应发送回FRENCH文本!有趣的不是它。

我已经登录到服务器并且我已经监控了日志,我很惊讶地看到我的所有请求都没有到达我的服务器并且日志显示旧值,我对自己说也许我的android中没有互联网设备,所以我已经删除了应用程序并重新安装它,日志文件开始与我的手机请求跳舞..所以设备有互联网连接,它正在正确调用服务器..

所以我认为Volley配置可能需要一些tweeking才能在不需要时缓存,而不是来自我的应用程序的示例代码:

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();
    }

欢迎任何帮助或想法。

1 个答案:

答案 0 :(得分:3)

尝试在

中添加req.setShouldCache(false);
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);
 }

之前

getRequestQueue().add(req);