Bugagull Bugagull - 1 year ago 60
Android Question

Unsuccessful using SharedPreferences to save score in game. What am I doing wrong?

I've made a very basic clicker game. The problem is that every time I close the app, the score resets to zero. I read up on SharedPreferences, but the ones I've created to save and retrieve the data don't work. Here is my code:

public class MainActivity extends Activity implements OnClickListener{

TextView textView1;
EditText editText1;
Button button1;
int counter = 0;

public void onCreate(Bundle savedInstanceState){

{textView1 = (TextView)findViewById(R.id.textView1);
editText1 = (EditText)findViewById(R.id.editText1);
button1 = (Button)findViewById(R.id.button1);

protected void onStop()
SharedPreferences prefs = this.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", counter);

protected void onStart()
SharedPreferences prefs = this.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE);
int defaultValue = 0;
int counter = prefs.getInt("key", defaultValue);}

public void onClick(View v){
if (v == button1){

On line 30 the "counter" says unable to access variable. Are there any solutions to this? Any help would be appreciated; I've tried reading more documentation,but I can't make any sense of it.

Answer Source

You have redeclared counter variable and it lost scope to be accessed in entire class.

int counter = prefs.getInt("key", defaultValue);

remove int declaration again in the onStart() method


 counter = prefs.getInt("key", defaultValue);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download