Java – Use SharedPrefernces to sum integers from RecyclerView

Use SharedPrefernces to sum integers from RecyclerView… here is a solution to the problem.

Use SharedPrefernces to sum integers from RecyclerView

I’m trying to create an app that calculates time.
My situation:
I have a RecyclerView with many elements, each with a different time property.

Now, when clicking on

one element, and then clicking on another, I want to sum all these properties and display the final result in another activity.
So what I want to do is use SharedPrefernces to achieve this:

private void getTime(int time) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
        int time0 = sharedPreferences.getInt("TimeRetrieve", 0);

int sum = time0 + time;

SharedPreferences sharedPreferences2 = mContext.getSharedPreferences("sharedPrefs", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences2.edit();
        editor.putInt("Time", sum);


TimeRetrieve gets the total time displayed on the TextView, so it of course defaults to 0 if it is the first time.
After that, it should add the retrieved int to the int of the Item that was just clicked and then saved in another SharedPref: Time.

Time is

sent to TextView, where it is retrieved by TimeRetrieve

But his doesn’t work…


First, you used 2 different keys: TimeRetrieve and Time. So, you can’t calculate the sum.
Secondly Why use 2 SharedPreferences objects? Only one is needed.
Third, you don’t need to use SharedPreferences here. You simply sum what you want in one variable and pass it to other activities with extra bundles.

Related Problems and Solutions