title: How to retain variable values in a fragment so when the fragment is launched again the value persists?
body: <p>I'm making a step counting app that uses navigationview to navigate between different parts of the application and I'm using a fragment for each view, I've setup the Sensor code with a fragment and I store the value in a variable but every time I navigate to another fragment the value of step count is lost and starts from zero. I want the value to remain when I navigate between the different fragments. </p>
  
  <pre><code>import android.app.Fragment;
  import android.content.Context;
  import android.hardware.Sensor;
  import android.hardware.SensorEvent;
  import android.hardware.SensorEventListener;
  import android.hardware.SensorManager;
  import android.os.Bundle;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.Button;
  import android.widget.RelativeLayout;
  import android.widget.TextView;
  
  public class HomeFragment extends Fragment implements SensorEventListener {
  
  SensorManager sensorManager;
  TextView tv_steps;
  boolean running = false;
  View myView;
  
  int initialStepCount = 0;
  int stepCount = 0;
  
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      myView = inflater.inflate(R.layout.home_layout, container, false);
  
      // null pointer exception
      // la fragmenta chon view agarrenitawa and make sure null nia
  
      RelativeLayout rl = (RelativeLayout) inflater.inflate(R.layout.home_layout, container, false);
      tv_steps = (TextView) rl.findViewById(R.id.tv_steps);
      sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
  
      return rl;
  }
  
  @Override
  public void onResume() {
      super.onResume();
      running = true;
      Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
      if (countSensor != null) {
          sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_FASTEST);
      } else {
      }
  }
  
  @Override
  public void onPause() {
      super.onPause();
      running = false;
      // unregister
      //sensorManager.unregisterListener(this);
  }
  
  @Override
  public void onSensorChanged(SensorEvent event) {
      if (initialStepCount == 0) {
          initialStepCount = (int) event.values[0];
      }
  
      stepCount = (int)event.values[0] - initialStepCount;
  
      if (running) {
          tv_steps.setText(String.valueOf(stepCount));
  
      }
  }
  
  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {
  
  }
  }
  </code></pre>