2017-09-24 66 views
0

任何人都可以請幫助我我無法弄清代碼中的問題。我只想在應用程序啓動或活動重新加載時加載一次json響應,但每次在應用程序啓動時都會在recylerview中加載json響應兩次,並且在我的情況下從服務器獲取兩個副本,然後在recylerview中共有50個新聞頻道25新聞頻道json數據在重新加載應用程序或打開應用程序時在recylerview中重複兩次

public class General extends Fragment 
    { 

     private static final String 
     URL = "https://newsapi.org/v1/sources?language=en&category=general&apiKey=0e1b2f7bc6bd4e1fbe0b40bea257dc97"; 
     private final int android_image_urls[] = 
     { 
     R.drawable.abcnews, 
     R.drawable.aljazeera, 
     R.drawable.associatedpress, 
     R.drawable.bbcnews, 
     R.drawable.cnn, 
     R.drawable.googlenews, 
     R.drawable.independent, 
     R.drawable.metro, 
     R.drawable.mirror, 
     R.drawable.newsweek, 
     R.drawable.newyorkmagazine, 
     R.drawable.reddit, 
     R.drawable.reuters, 
     R.drawable.theguardianau, 
     R.drawable.theguardianuk, 
     R.drawable.thehindu, 
     R.drawable.thehuffingtonpost, 
     R.drawable.thenewyorktimes, 
     R.drawable.thetelegraph, 
     R.drawable.thetimesofindia, 
     R.drawable.thewashingtonpost, 
     R.drawable.time, 
     R.drawable.usatoday 
    }; 

    private RecyclerView recyclerView; 
    private RecyclerView.Adapter adapter; 
    private ArrayList<AndroidVersion> androidVersions; 

    TextView textView; 

    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
    View rootView = inflater.inflate(R.layout.layout_general, container, false); 

    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view); 
    recyclerView.setHasFixedSize(true); 
    RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getContext(),3); 
    recyclerView.setLayoutManager(layoutManager); 
    textView = (TextView) rootView.findViewById(R.id.empty_view); 
    androidVersions = new ArrayList<>(); 
    loadRecyclerViewData(); 
    return rootView; 
    } 


    public void loadRecyclerViewData() { 

    final ProgressDialog progressDialog = new ProgressDialog(getContext()); 
    progressDialog.setMessage("Loading Data...."); 
    progressDialog.show(); 


    JsonObjectRequest data = new JsonObjectRequest(Request.Method.GET, URL,null, 

      new Response.Listener<JSONObject>() { 

       @Override 
       public void onResponse(JSONObject response) { 
        progressDialog.dismiss(); 

        try { 
         JSONObject jsonObject = new JSONObject(String.valueOf(response)); 

         JSONArray array = jsonObject.getJSONArray("sources"); 

         for (int i = 0; i < array.length(); i++) { 
          JSONObject o = array.getJSONObject(i); 
          AndroidVersion item = new AndroidVersion(

            o.getString("name"), 
            android_image_urls[i], 
            o.getString("category") 
          ); 
          androidVersions.add(item); 

         } 


         if (androidVersions.isEmpty()) { 
          recyclerView.setVisibility(View.GONE); 
          textView.setVisibility(View.VISIBLE); 
         } else { 
          recyclerView.setVisibility(View.VISIBLE); 
          textView.setVisibility(View.GONE); 
         } 

         adapter = new DataAdapter(androidVersions, getContext()); 
         recyclerView.setAdapter(adapter); 
         adapter.notifyDataSetChanged(); 

        } catch (JSONException e) { 
         e.printStackTrace(); 
        } 

       } 
      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      progressDialog.dismiss(); 
      Toast.makeText(getContext(),"No Internet Connection", Toast.LENGTH_SHORT).show(); 

     } 
    }) 
    { 
    @Override 
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) { 
    try { 
     Cache.Entry cacheEntry = HttpHeaderParser.parseCacheHeaders(response); 
     if (cacheEntry == null) { 
      cacheEntry = new Cache.Entry(); 
     } 
     final long cacheHitButRefreshed = 3 * 60*1000; // in 3 minutes cache will be hit, but also refreshed on background 
     final long cacheExpired = 24 * 60 * 1000 ; //24 * 60 * 60 * 1000; // in 24 hours this cache entry expires completely 
     long now = System.currentTimeMillis(); 
     final long softExpire = now + cacheHitButRefreshed; 
     final long ttl = now + cacheExpired; 
     cacheEntry.data = response.data; 
     cacheEntry.softTtl = softExpire; 
     cacheEntry.ttl = ttl; 
     String headerValue; 
     headerValue = response.headers.get("Date"); 
     if (headerValue != null) { 
      cacheEntry.serverDate = HttpHeaderParser.parseDateAsEpoch(headerValue); 
     } 
     headerValue = response.headers.get("Last-Modified"); 

     if (headerValue != null) 
     { 
      cacheEntry.lastModified = HttpHeaderParser.parseDateAsEpoch(headerValue); 
     } 
     cacheEntry.responseHeaders = response.headers; 
     final String jsonString = new String(response.data, 
       HttpHeaderParser.parseCharset(response.headers)); 
     return Response.success(new JSONObject(jsonString), cacheEntry); 
    } catch (UnsupportedEncodingException e) { 
     return Response.error(new ParseError(e)); 
    } catch (JSONException e) { 
     return Response.error(new ParseError(e)); 
    } 
    } 
     @Override 
     protected void deliverResponse(JSONObject response) { 
      super.deliverResponse(response); 
     } 

     @Override 
     public void deliverError(VolleyError error) { 
      super.deliverError(error); 
     } 

     @Override 
     protected VolleyError parseNetworkError(VolleyError volleyError) { 
      return super.parseNetworkError(volleyError); 
     } 
}; 

RequestQueue requestQueue = Volley.newRequestQueue(getContext()); 
    requestQueue.add(data); 
} 

}

+0

在向其添加項目之前清除ArrayList androidVersions.clear() 並沒有使用adapter.notifyDataSetChanged(),因此您可以將其刪除。 –

+0

非常感謝你Geeta它像魅力一樣工作。 – Adam

回答

0

你的代碼是正確的,但絕不能有重複的數據,請嘗試刪除數據

+0

rajendra你正在寫關於刪除數據的捕獲,我嘗試它的工作原理,但我想在應用程序啓動時在recylerview中存儲至少少量的數據,以便用戶可以查看或讀取離線時最近成功加載的數據的一些,只要互聯網連接不可用,那麼我應該怎麼做呢? – Adam

0

在你onResponse你不是正在打掃androidVersions列表的緩存。因此,每次執行請求時,都會向列表中添加新項目。很可能你的請求被執行兩次(loadRecyclerViewData()被調用兩次?)。

每次填入onResponse時,請嘗試清理或重新創建androidVersions

+0

感謝algrid爲您的解決方案,但你能解釋我說你詳細說什麼像一塊程序來清除列表,因爲我第一次做這件事 – Adam

+0

請告訴我應該如何實現你所說的編程? – Adam

相關問題