Kunal
Kunal

Reputation: 13

How to use SharedPreferences to store int that is incremented everytime the user clicks a button & retrieve value next time the app is launched

Im a beginner to Android Dev, and Ive been working on a pretty straightforward voting app for school.

Basically I've created objects in multiple activities that act as int counters to record votes(in form of clicks) for various posts. I have achieved this and also am able to view results for all the counters in a different activity. Also, the activity shifts to a new activity for the next position in the voting system automatically.

I realised that I would lose all the data/votes from the objects(counters) if the app was killed or crashed. Therefore, i tried implementing shared preferences to store and update the count of votes when the button was clicked.

However, my app crashes when I use the code to reassign a shared preference variable as the counter objects value.

I cannot seem to understand what and where to fix my code so that the counter resumes from last value. Below is my code:

public class SPL extends AppCompatActivity {

SharedPreferences retrieve = getApplicationContext().getSharedPreferences("Result", MODE_PRIVATE);

public int spl1count = retrieve.getInt("HB1", 0);
public int spl2count = retrieve.getInt("HB2", 0);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_spl);

    final Button spl1vb = (Button) findViewById(R.id.spl1vb);
    final Button spl2vb = (Button) findViewById(R.id.spl2vb);


    spl1vb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spl1count ++;
            SharedPreferences sharedPref = getSharedPreferences("Result", Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPref.edit();

            editor.putInt("HB1", spl1count);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Saved ", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getApplicationContext(), ASPL.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    });


    spl2vb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spl2count ++;
            SharedPreferences sharedPref = getSharedPreferences("Result", Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPref.edit();

            editor.putInt("HB2", spl2count);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Saved ", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getApplicationContext(), ASPL.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    });


}

The app crashes and after looking at the log it tells me there is an error on the line where I used a shared preference 'retrieved' to get back old data to fit into the counter.

If i remove this, the counter sets back to 0 when it is launched again, which i believe is because the counter isn't actually being set to a shared preference value.

Here is the code by which I am collecting results from shared preference in another activity:

  SharedPreferences sharedPref = getSharedPreferences("Result", Context.MODE_PRIVATE);

    final int spl1r = sharedPref.getInt("HB1", 0);
    final int spl2r = sharedPref.getInt("HB2", 0);

Then I use an alert dialog box to display spl1r and spl2r.

I've spent hours on the internet searching for a solution but none have worked for me. Any help would be appreciated. Thanks in Advance


So I updated the code based on Evin's answer, but my code still crashes, this time in the OnCreate

Here is my new code:

     public class SPL extends AppCompatActivity {


SharedPreferences retrieve;
public int spl1count;
public int spl2count;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    retrieve = getApplicationContext().getSharedPreferences("Result", MODE_PRIVATE);
    spl1count = retrieve.getInt("HB1", 0);
    spl2count = retrieve.getInt("HB2", 0);

     Button spl1vb = (Button) findViewById(R.id.spl1vb);
     Button spl2vb = (Button) findViewById(R.id.spl2vb);



    spl1vb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spl1count ++;
            SharedPreferences sharedPref = getSharedPreferences("Result", Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPref.edit();

            editor.putInt("HB1", spl1count);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Saved ", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getApplicationContext(), ASPL.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    });


    spl2vb.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            spl2count ++;
            SharedPreferences sharedPref = getSharedPreferences("Result", Context.MODE_PRIVATE);

            SharedPreferences.Editor editor = sharedPref.edit();

            editor.putInt("HB2", spl2count);
            editor.apply();
            Toast.makeText(getApplicationContext(),"Saved ", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(getApplicationContext(), ASPL.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            finish();
        }
    });


}

Am I still doing something wrong? Thank you.

Upvotes: 1

Views: 273

Answers (1)

Evin1_
Evin1_

Reputation: 12866

Put these lines inside the onCreate:

SharedPreferences retrieve = getApplicationContext().getSharedPreferences("Result", MODE_PRIVATE);

public int spl1count = retrieve.getInt("HB1", 0);
public int spl2count = retrieve.getInt("HB2", 0);

You are initializing them when they have no reference to any Android context yet (which is built in the onCreate method of the Activity/Application) that's why the getSharedPreferences method of the ApplicationContext will be a null reference.


If you still want to declare these values as member variables, your class would look something like (splitting the declaration and assignment):

public class SPL extends AppCompatActivity {
    SharedPreferences retrieve;
    public int spl1count;
    public int spl2count;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_spl);

        retrieve = getApplicationContext().getSharedPreferences("Result", MODE_PRIVATE);
        spl1count = retrieve.getInt("HB1", 0);
        spl2count = retrieve.getInt("HB2", 0);

        final Button spl1vb = (Button) findViewById(R.id.btn1);
        final Button spl2vb = (Button) findViewById(R.id.btn2);

       /* Your listeners */
    }
}

Upvotes: 2

Related Questions