任何人都可以請幫助我我無法弄清代碼中的問題。我只想在應用程序啓動或活動重新加載時加載一次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);
}
}
在向其添加項目之前清除ArrayList androidVersions.clear() 並沒有使用adapter.notifyDataSetChanged(),因此您可以將其刪除。 –
非常感謝你Geeta它像魅力一樣工作。 – Adam