I have a Fragment called HomeFragment contain GridView list from JSON that requested using Volley. And its success without any problem to display the JSON, but the problem is when after i go to another fragment or activity then back again to HomeFragment, the JSON in GridView is increased/added with the same data again.
How to stop that so the data is not increased.
there is my code in HomeFragment
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_home, container, false);;
getActivity().setTitle("Dashboard");
final HashMap<String, String> role = sharedPreference.getDetails();
String url = "http://myurl";
RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());
StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.getJSONObject(i);
String menu_id = data.getString("menu_id");
String menu_name = data.getString("menu_name");
HashMap<String, String> row = new HashMap<>();
row.put("menu_id", menu_id);
row.put("menu_name", menu_name);
menulist.add(row);
Log.e(TAG, "onResponse: " + menulist );
GridView gridView = (GridView) view.findViewById(R.id.menu_item_grid);
ListAdapter listAdapter = new SimpleAdapter(getContext(), menulist,
R.layout.home_menu, new String[]{"menu_name"},
new int[]{R.id.item_grid});
gridView.setAdapter(listAdapter);
}
} catch (JSONException ex) {
ex.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getContext(), "error : " + error, Toast.LENGTH_SHORT).show();
}
});
queue.add(stringRequest);
return view;
}
Thanks..
2
Answers
When you go to another fragment/activity, your HomeFragment doesn’t get destroyed immediately, so its values (
menulist
) are still preserved. But when you get back to it, the view is created again, and the new data from the API is added to the previous list.In your
onResponse()
method, clear themenulist
withmenulist.clear()
This doesn’t reduce API calls but keeps the data consistent.
When you go from
HomeFragmnt
toOtherFragment
and when pressed backonCreateView()
call again inHomeFragment
so your request call again so your data is duplicate.You should Make BaseFragment do the following code. it will help you.
Java Help
BaseFragment.java
HomeFragment.java
Kotlin Help
BaseFragment.kt
HomeFragment.kt