This is my code:
package com.example.sharedprefs;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
int i = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doThis (View view){
i++;
SharedPreferences sharedPref = getSharedPreferences("FileName",MODE_PRIVATE);
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putInt("userChoice",i);
prefEditor.commit();
int number = sharedPref.getInt("userChoice", 0);
Toast.makeText(getApplicationContext(), number + "" , Toast.LENGTH_LONG).show();
this.finish();
}
}
When the app runs and I run it again. I constantly get “1” as a toast. I’m trying to get 1 and 2 and 3 and so on. Any ideas? I know that it’s not the program, it’s the “programmer” at this point. Thanks in advance
Answer given in the first comment; SharedPreferences Logical Error.
You should put the following code
in the
onCreate()-method in your Activity.In your code, i is 0 every time you start this Activity.