0

I generate a random number when I open the application and I save this number with Sharedpreferences. This is my code:

public class MainActivity extends AppCompatActivity {

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

        Random r = new Random();
        int number = r.nextInt(100);

        SharedPreferences randomnumber = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = randomnumber.edit();
        editor.putInt("intValue",number);
        editor.commit();
    }
}

Can I collect old and new numbers when I open the application?

Johny
  • 45
  • 10

2 Answers2

2

You are overriding the old value with the new value with this

editor.putInt("intValue",number);

That's why you will always see one value for it. You could either have different field names or use an array for example like this How can I store an integer array in SharedPreferences?

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
1

Get old value before it set new value..

    Random r = new Random();
    int number = r.nextInt(100);

    SharedPreferences randomnumber = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

    String old = randomnumber.getString('intValue');  // old value

    SharedPreferences.Editor editor = randomnumber.edit();
    editor.putInt("intValue",number); // set new value
    editor.apply();
ZeroOne
  • 8,996
  • 4
  • 27
  • 45