Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

}
like image 341
volunteer softwares Avatar asked Mar 22 '17 03:03

volunteer softwares


People also ask

How can we prevent onCreateView when back button is pressed in fragment in Android?

Create an init() method where you do all initialization and server calls and logically branch out call to init() method whenever you don't want to call init().

Which method is called when back button is pressed in fragment?

onBackPressed() method. In its body, we list all fragments attached to activity and for this implementing our BaseFragment class/interface we notify them about the new back-press event.

Is onCreate or onCreateView called first?

onCreate() is called to do initial creation of the fragment. onCreateView() is called by Android once the Fragment should inflate a view. onViewCreated() is called after onCreateView() and ensures that the fragment's root view is non-null .

What is called after onCreateView?

The onActivityCreated() method is called after onCreateView() and before onViewStateRestored() . onDestroyView() : Called when the View previously created by onCreateView() has been detached from the Fragment . This call can occur if the host Activity has stopped, or the Activity has removed the Fragment .


1 Answers

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.

like image 87
VikasGoyal Avatar answered Oct 16 '22 20:10

VikasGoyal