Bugagull Bugagull - 11 days ago 6
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;

@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);

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

@Override
protected void onStop()
{super.onStop();
SharedPreferences prefs = this.getSharedPreferences("MySharedPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("key", counter);
editor.commit();}

@Override
protected void onStart()
{super.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){
counter++;
editText1.setText(Integer.toString(counter));}}}


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

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

into

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