android-fragmentssavestateonbackpressedrecreate

android fragment reloading (onCreate) each time when back Button pressed


I am new in android using fragments in my Project. first time my fragment is creating then api called and get data load in fragment. here when i clicked at any item i replaced fragment by another fragment there also another api called and load data to fragment. now here problem situation generated for me. from here i back Button pressed.

fragment reloading same as first time creating but it should be show data as i left before going to next fragment.

so please provide me solution how i can get same data as i left means savedInstanceState data.

im my first fragment getCategory method call Api and get Data first time when i choose any category i replace fragment with another fragment but when i m returning same getCategory method recall perform same process as it first time.

fragment should not call api method again on backpressed it should show same category on this i clicked before.

my first fragment where calling api......

public class LandingFragment extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
     private String mParam1;
     private String mParam2;

     private GridLayoutManager gridLayoutManager;
     private static RecyclerView category_Grid;
     private Fragment myFragment = null;
     ProgressBar mProgressView;
     View mLoginFormView;
     private Category category;
     private CategoryAdapter categoryAdapter;
     private List<CategoryObject> rowListItem;
     private String productId;
     private OnFragmentInteractionListener mListener;

    public LandingFragment() {
       // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
      *
      * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment LandingFragment.
     */
     // TODO: Rename and change types and number of parameters
     public static LandingFragment newInstance(String param1, String param2)    {
        LandingFragment fragment = new LandingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
     }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v= inflater.inflate(R.layout.fragment_landing, container, false);
        return v;
    }

     @Override
     public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

         initViews(view);
         RecyclerViewListeners();
     }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
           mListener.onFragmentInteraction(uri);
        }
    }

    @Override
     public void onAttach(Activity context) {
        super.onAttach(context);

        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
     }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
      * This interface must be implemented by activities that contain this
      * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     *     "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
     }

    private void initViews(final View v) {
        mLoginFormView = (View)v.findViewById(R.id.mainView);
        mProgressView = (ProgressBar)v.findViewById(R.id.login_progress);
        category_Grid = (RecyclerView)v.findViewById(R.id.cat_grid);
        category_Grid.setHasFixedSize(true);
        gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        category_Grid.setLayoutManager(gridLayoutManager);
     }

 private void RecyclerViewListeners(){
    category_Grid.addOnItemTouchListener(new    RecyclerTouchListener(getActivity(), category_Grid, new ItemClickListener(){
        @Override
        public void onClick(View view, int position) {

            String entityId = rowListItem.get(position).getCategoryId();
            String catName = rowListItem.get(position).getName();
            Integer ishave = rowListItem.get(position).getIshaveSubcategories();
            if(ishave==1) {
                myFragment = SubcategoryFragment.newInstance(""+catName, "" + entityId);
                ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
            }else{
                myFragment = ProductListFragment.newInstance("", "" + entityId);
                ActivityUtils.launchFragementWithAnimation(myFragment, getActivity());
            }
        }

        @Override
        public void onLongClick(View view, int position) {

        }
    }));
}

public void getCategory() {
    showProgress(true);
    String URL = getResources().getString(R.string.category_api);
    StringRequest req = new StringRequest(Request.Method.POST,URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            VolleyLog.v("Response:%n %s", response);
            Gson gson = new GsonBuilder().serializeNulls().create();
            try {
                JSONObject jsonObject = new JSONObject(response);
                if (jsonObject.getString("status").equals(getResources().getString(R.string.response_success))){
                    category = gson.fromJson(response, Category.class);
                    rowListItem = category.getCategory();
                    if(navigationUpdated){
                        someEventListener.someEvent(rowListItem);
                        navigationUpdated = false;
                    }
                    Log.d("CATEGORYID::::::::",""+rowListItem.get(1).getCategoryId());
                    categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
                    category_Grid.setAdapter(categoryAdapter);
                    categoryAdapter.notifyDataSetChanged();


                    return;
                }
                else if (jsonObject.getString("status").equals(getResources().getString(R.string.login_Er_respose))){
                    Log.e("","ERRORRRRRR");
                    return;
                }
            } catch (JSONException e) {
                showProgress(false);
                Log.e("My App", "Could not parse malformed JSON: \"" + response + "\"");
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
              showProgress(false);
              VolleyLog.e("Error: ", error.getMessage());
        }
    }){
        @Override
        protected Map<String,String> getParams(){
            Map<String,String> params = new HashMap<String, String>();
            return params;
        }

        @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            Map<String,String> params = new HashMap<String, String>();
            params.put("Content-Type","application/x-www-form-urlencoded");
            return params;
        }
    };
    AppController.getInstance().addToRequestQueue(req);
}

    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        int shortAnimTime =   getResources().getInteger(android.R.integer.config_shortAnimTime);

        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            }
        });

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    } else {

        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
    }
}

Solution

  • for more clarification i want to tell.. how i implement the @Bhvk_AndroidBee solution

    fragment backpressed call onActivityCreated Method so first overridethis method in fragment

      @Override
        public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);
    
          //here you can check null condition for rowListItem
        }
    }
    

    inside onActivityCreated method I checked the condition like that

        @Override
         public void onActivityCreated(Bundle savedInstanceState) {
           super.onActivityCreated(savedInstanceState);
            if(rowListItem!=null){
    
               categoryAdapter = new CategoryAdapter(getActivity(),rowListItem);
               category_Grid.setAdapter(categoryAdapter);
               categoryAdapter.notifyDataSetChanged();
    
           }else {
    
            //call the method for first time creating your view
    
               getCategory();
    
           }
        }
    

    hope this would be helpfull for more strugglers like me...