Why does oncreateview of the current fragment gets called on pressing the back button?
E

1

7

I am trying to retrieve the fragment from the backstack. It is getting retrieved but the issue is that on pressing the back button the oncreate view and subsequent lifecyce methods of current fragment is also getting called. Here's my code to put the fragment in the backstack:

fragment=new FileTrackingFragment();
bundle=new Bundle();
bundle.putString("name","Dak Monitoring");
bundle.putInt("num",2);
fragment.setArguments(bundle);
ft.replace(R.id.parent, fragment, fragment.getClass().getName());
ft.addToBackStack(fragment.getClass().getName());
ft.commit();
break;

Here's the code of the fragment:

package com.example.rajvirsingh.epunjaboffice.DakMonitoring;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.percent.PercentRelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.rajvirsingh.epunjaboffice.FileTracking.HistoryAdapter;
import com.example.rajvirsingh.epunjaboffice.MainActivity;
import com.example.rajvirsingh.epunjaboffice.R;
import com.example.rajvirsingh.epunjaboffice.Utility.Constants;
import com.example.rajvirsingh.epunjaboffice.Utility.SessionManager;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.json.JSONArray;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

/**
 * Created by rajvirsingh on 07/03/17.
 */

public class ConsolidatedReportFragment extends Fragment implements AdapterView.OnItemSelectedListener {
  SessionManager sessionManager;
  JSONArray consolidatedRJsonArray;
  String userCode,branchCode;
  MainActivity mainActivity;
  Spinner spinDuration;
  String selectedDuration="";
  ProgressDialog pDialog;
  TextView error,serial;
  PercentRelativeLayout pl;
  PercentRelativeLayout ll;
  RecyclerView recyclerView;
  AsyncHttpClient client = new AsyncHttpClient();
  String []durationValues={"This Week","This Month","This Year","Total"};


  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_dak_monitoring_consolidated,container,false);
  }


  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    sessionManager=SessionManager.NewInstance(activity);
    userCode=sessionManager.pref.getString("usercode","");
    branchCode=sessionManager.pref.getString("branchcode","");
    mainActivity=(MainActivity) getActivity();
    if(((AppCompatActivity) getActivity()).getSupportActionBar()!=null) {
      ((AppCompatActivity) getActivity()).getSupportActionBar().show();
      mainActivity.setToolbarTitle("Consolidated Report");
      mainActivity.unlockDrawer();
      mainActivity.loadNavigationMenu(R.menu.menu_dak_monitoring);
    }
  }

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

    pDialog = new ProgressDialog(getActivity(),R.style.DialogStyle);
    pDialog.setMessage("Loading...");
    pDialog.setTitle("Office Management");
    pDialog.setIndeterminate(true);
    pDialog.setCancelable(true);

    sessionManager=SessionManager.NewInstance(getActivity());

    error=(TextView)view.findViewById(R.id.err);
    serial=(TextView)view.findViewById(R.id.serial);


    spinDuration=(Spinner)view.findViewById(R.id.spin_duration);
    ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,durationValues);
    arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinDuration.setAdapter(arrayAdapter);
    spinDuration.setOnItemSelectedListener(this);
    spinDuration.setSelection(0);
    selectedDuration="1";

    pl=(PercentRelativeLayout)view.findViewById(R.id.percentile);

    ll=(PercentRelativeLayout) view.findViewById(R.id.ll1);
    recyclerView=(RecyclerView)view.findViewById(R.id.recyclerView);

    if(Constants.isOnline(getActivity()))
    {

      getConsolidatedReport();
    }
  }

  void getConsolidatedReport()
  {
    RequestParams params = new RequestParams();
    params.put("_userMasterCode",userCode);
    params.put("_parameter", selectedDuration);
    String url=getString(R.string.urlGetConsolidatedMonitoringReport);

    client.get(url, params, new TextHttpResponseHandler() {
      @Override
      public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
        pDialog.dismiss();
        ll.setVisibility(View.GONE);
        recyclerView.setVisibility(View.GONE);
        error.setVisibility(View.VISIBLE);
        if(getView()!=null)
          Snackbar.make(getView(), "Error!", Snackbar.LENGTH_LONG).show();
      }

      @Override
      public void onSuccess(int statusCode, Header[] headers, String responseString) {

        try {
          pDialog.dismiss();
          int p1 = responseString.indexOf(">");
          int p2 = responseString.lastIndexOf("<");
          String r = responseString.substring(p1 + 1, p2);
          p1 = r.indexOf(">");
          r = r.substring(p1 + 1, r.length());
          ll.setVisibility(View.VISIBLE);
          recyclerView.setVisibility(View.VISIBLE);
          error.setVisibility(View.GONE);
          consolidatedRJsonArray = new JSONArray(r);
          ConsolidatedReportAdapter consolidatedReportAdapter=new ConsolidatedReportAdapter(consolidatedRJsonArray,getActivity());
          recyclerView.setAdapter(consolidatedReportAdapter);
          recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        } catch (Exception e) {
          if (getActivity() != null && isAdded()) {
            ll.setVisibility(View.GONE);
            recyclerView.setVisibility(View.GONE);
            error.setVisibility(View.VISIBLE);
            if(getView()!=null)
              Snackbar.make(getView(), "No Information Exist! For Selection", Snackbar.LENGTH_LONG).show();
            else
              Toast.makeText(getActivity(),"No Information Exist! For Selection",Toast.LENGTH_LONG).show();
            pDialog.dismiss();
          }
        }
      }
    });
  }

  @Override
  public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    switch (parent.getId())
    {
      case R.id.spin_duration:
        selectedDuration=String.valueOf(position+1);
        getConsolidatedReport();
        break;
    }
  }

  @Override
  public void onNothingSelected(AdapterView<?> parent) {

  }

  @Override
  public void onPause() {
    super.onPause();
    pDialog.dismiss();
  }

  @Override
  public void onStop() {
    client.cancelAllRequests(true);
    super.onStop();
  }

}
Enthalpy answered 22/3, 2017 at 3:43 Comment(0)
B
1

It will be going to call as your view is destroyed when you move to the next fragment so it will demand view again on pressing back button and that should be the approach as keeping fragments view(which are currently not visible) in memory will cause memory issue later on. It's onCreate() method which is not going to call again.

If you don't want to call onCreateView on back press then use ft.add(R.id.parent, fragment, fragment.getClass().getName());

For more details about how fragment stack behave please refer here.

Blinny answered 22/3, 2017 at 3:58 Comment(6)
The problem is that the oncreateview of the current view that is the view on which I am currently present which is getting called. I am not talking about the view on which I am going back.Enthalpy
Can you provide the complete code of current visible fragment whose onCreateView is getting call on backpress.Blinny
Only for try, can you once run your code again after commenting onStop() method of your current fragment.Blinny
Tried but it didnt make any differenceEnthalpy
on the above code you pushing FileTrackingFragment and below you have provided the code for ConsolidatedReportFragment. What is the actual stack of your fragments can you please explain. If FileTrackingFragment is top one fragment where you press back button then you need to provide the code of FileTrackingFragment here and if it ConsolidatedReportFragment then please provide the code how are you pushing ConsolidatedReportFragment in stack.Blinny
The FileTrackingFragment is getting replaced by using replace command with ConsolidatedReportFragment. But I am not pushing that to back stack. So, what happens is that on pressing the back button from ConsolidatedReportFragment, I go back to the fragment from the backstack but on pressing back, the oncreateview of ConsolidatedReport is getting called again. Tht is weird.Enthalpy

© 2022 - 2024 — McMap. All rights reserved.