Search code examples
androidbundle

I am getting variables with bundle but its not updating


im trying to develop a pedometer. I got steps with sensor but ı need send them to fragment. For that ı used a bundle. Steps variable is passing to fragment but its only getting first value. That first value is zero and i gave that value when i create variable. This value is updating ım seeing that on stepsTextview. But in bundle not. How can ı get updated variables when sensor changed?

Activity Code:

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    if (sensorEvent.sensor == stepCounter){
        stepCount = (int) sensorEvent.values[0];
        textView.setText(String.valueOf(stepCount));
        CountStepFragment fragment = new CountStepFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("Adım", stepCount);
        fragment.setArguments(bundle);
    }

}

Fragment Code:

Bundle bundle = this.getArguments();
    if (bundle != null) {
        myInt = bundle.getInt("Adım",0);
        Log.i("sda",String.valueOf(myInt));

    }

Solution

  • what you're doing here is passing that variable one time

    Bundle bundle = new Bundle();
    bundle.putInt("Adım", stepCount);
    fragment.setArguments(bundle);
    

    this only happens when you create the fragment

    in order to achieve this in your fragment, you'll have to find a way to implement this code inside the actual fragment :

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        if (sensorEvent.sensor == stepCounter){
            stepCount = (int) sensorEvent.values[0];
            //now use stepCount to update your fragment
        }
    
    }