skip to Main Content

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;
}

the result

Thanks..

2

Answers


  1. 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 the menulist with menulist.clear()

    menulist.clear();
    JSONObject obj = new JSONObject(response);
    JSONArray array = obj.getJSONArray("data");
    

    This doesn’t reduce API calls but keeps the data consistent.

    Login or Signup to reply.
  2. When you go from HomeFragmnt to OtherFragment and when pressed back onCreateView() call again in HomeFragment 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

    public class BaseFragment<T> extends Fragment {
    
        public boolean hasInitializedRootView = false;
    
        private View rootView;
    
        public View getPersistentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState, int layout){
            if (rootView == null) {
                rootView = inflater.inflate(layout, container, false);
            } else {
                ((ViewGroup) rootView.getParent()).removeView(rootView);
            }
    
            return rootView;
        }
        
    }
    

    HomeFragment.java

    public class HomeFragment extends BaseFragment<View> {
    
        public View onCreateView(@NonNull LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
    
            return getPersistentView(inflater, container, savedInstanceState, R.layout.fragment_home);
        }
    
    
        @Override
        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);
    
            if (!hasInitializedRootView) {
                hasInitializedRootView = true;
    
                // Do your work here
    
            }
    
        }
    }
    

    Kotlin Help

    BaseFragment.kt

    open class BaseFragment<T : View> : Fragment() {
    
        var hasInitializedRootView = false
        private var rootView: View? = null
    
        fun getPersistentView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?,
            layout: Int
        ): View? {
            if (rootView == null) {
                rootView = inflater.inflate(layout, container, false)
            } else {
    
                (rootView?.parent as? ViewGroup)?.removeView(rootView)
            }
    
            return rootView
        }
    
    }
    

    HomeFragment.kt

    class HomeFragment : BaseFragment<View>() {
        
        override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
        ): View? {
            return getPersistentView(inflater, container, savedInstanceState, R.layout.fragment_home)
        }
    
    
        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
            super.onViewCreated(view, savedInstanceState)
    
            if (!hasInitializedRootView) {
                hasInitializedRootView = true
    
                // Do your work here
    
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search