I have a BottomNavigationView
displaying Fragments
, in my first fragment I'm using volley to fetch JSON data and populate it in a RecyclerView
like below:
private void loadRecyclerViewData() {
StringRequest stringRequest = new StringRequest(Request.Method.GET,
URL_DATA,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
bar.setVisibility(View.GONE);
try {
JSONArray array = new JSONArray(s);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
ListItem item = new ListItem(
o.getString("name"),
o.getString("bio"),
o.getString("imageurl")
);
listItems.add(item);
}
adapter = new MyAdapter(listItems, getContext());
rv.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
bar.setVisibility(View.GONE);
Toast.makeText(getContext(), volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
});
RequestQueue requestQueue = Volley.newRequestQueue(getContext());
requestQueue.add(stringRequest);
}
The above gets called in my fragments onCreateView
.
It gets displayed like I want it to, but, this is where the issue is. When I go to another fragment and return (by using the BottomNavigationView
), then onCreateView
will be called again and the data will load again.
a Good example of this is the YouTube and Instagram app, where the data doesn't get reloaded every time when switching between views.
My Question:
How can I navigate between fragments using BottomNavigationView
without calling onDestroyView
, or is there another way to avoid the issue I' having?
Here is a similar question.
EDIT 1 : Adding more context to the question
When selecting a item inside BottomNavigationView
it inflates/replaces a fragment, causing onCreateView
to be called. My method is being called within onCreateView
, this means that every time I "switch" between fragments, my method will be called again causing Volley to fetch the data again.