Search code examples
javaandroidandroid-fragmentssharedpreferences

How to count how many times a user has clicked a button and how to save it. Android Studio


I am currently making an Android app using android Studio, and one of the features it has is it collects how many times the user has clicked a certain button and stores it, and displays it on a bar graph. It's a mood tracker. However the counter is on a fragment and whenever I leave the app or the activity it just resets the value which is not what I want.

The code for the bar graph:

SharedPreferences preferences = requireActivity().getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);


        BarGraphSeries series1 = new BarGraphSeries<>(new DataPoint[] {
                new DataPoint(1, preferences.getInt("Elated", elatedTimes)),
                new DataPoint(2, preferences.getInt("Happy", happyTimes)),
                new DataPoint(3, preferences.getInt("Meh", mehTimes)),
                new DataPoint(4, preferences.getInt("Sad", sadTimes)),
                new DataPoint(5, preferences.getInt("Angry", angryTimes))
        });
        graphView.addSeries(series1);

// styling
        StaticLabelsFormatter staticLabelsFormatter = new StaticLabelsFormatter(graphView);
        staticLabelsFormatter.setHorizontalLabels(new String[] {"Elated", "Happy", "Meh", "Sad", "Angry"});
        graphView.getGridLabelRenderer().setLabelFormatter(staticLabelsFormatter);
        
        series1.setValueDependentColor(new ValueDependentColor<DataPoint>() {
            @Override
            public int get(DataPoint data) {
                return Color.rgb((int) data.getX()*255/4, (int) Math.abs(data.getY()*255/6), 100);
            }
        });

        series1.setSpacing(50);
        series1.setAnimated(true);
        graphView.getGridLabelRenderer().setLabelsSpace(8);
        graphView.getViewport().setMinY(0);
        graphView.getViewport().setYAxisBoundsManual(true);

// draw values on top
        series1.setDrawValuesOnTop(true);
        series1.setValuesOnTopColor(Color.RED);

The code for one of the moods to be saved:

elatedCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences preferences = requireActivity().getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = preferences.edit();
                editor.putInt("Happy", elatedTimes++);
                editor.apply();

                final Dialog elatedDialog = new Dialog(HomeFragment.this.getContext());
                elatedDialog.setContentView(R.layout.elated_dialog_design);
                elatedDialog.show();

                elatedDialogButton = (Button) elatedDialog.findViewById(R.id.elated_dialog_button);
                //Performing action on Button Click
                elatedDialogButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        final Intent intent;
                        intent = new Intent(getContext(), ventingPage.class);
                        startActivity(intent);
                    }

                });
            }
        });

(It is in onViewCreated())

And lastly the code for my onPause() which doesn't work:

@Override
    public void onPause(){
        SharedPreferences.Editor editor = requireActivity().getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE).edit();
        editor.putInt("Elated", elatedTimes);
        editor.apply();
        super.onPause();

    }

SO basically my question is

  1. How do I save an integer counter in a fragment and display it on a bar graph without it resetting?

Thanks so much!


Solution

  • You are overriding the elated value in SharedPreferences every time with session variable elatedTimes, instead prior to setting it, get the value first and set the sum of them like

    @Override
    public void onPause(){
       SharedPreferences prefs = requireActivity().getSharedPreferences("MY_PREFERENCES", Context.MODE_PRIVATE);
       int elatedCurrentValue = prefs.getInt("Elated",0); // get existing value
       int elatedNewValue = elatedCurrentValue + elatedTimes; //add it to session value
       SharedPreferences.Editor editor = prefs.edit();
       editor.putInt("Elated", elatedNewValue); // save updated value
       editor.apply();
    }