2014-11-25 104 views
2

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

任何幫助或想法,歡迎。

回答

3

嘗試

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