0

I need your help here.. I have the following code:

public class GameActivity extends Activity { TextView test1; String punkte, points; @Override public void onCreate(Bundle savedInstanceState) { test1 = (TextView) findViewById(R.id.test1); punkte = points; SharedPreferences load = getSharedPreferences(punkte, 0); points = load.getString("punkte", "0"); test1.setText(points); } public void mehrPunkte() { punkte = "3"; SharedPreferences load = getSharedPreferences(punkte, 0); points = load.getString("punkte", "0"); test1.setText(points); SharedPreferences save = getSharedPreferences(punkte, 0); save.edit().putString("punkte", punkte).commit(); } 

But it still shows "0" if i restart the app. What did I do wrong?

2
  • I see no call to mehrPunkte... Commented Jul 27, 2012 at 15:54
  • It's called in a onClick-method:public void onClick(View v) { mehrPunkte();} Commented Jul 27, 2012 at 15:55

2 Answers 2

3

The first parameter of getSharedPreferences is its name, and you save it to a different shared preferences, indicated by the value of the punkte variable. Try this instead:

final private static String SHARED_PREF_ID = "My shared preferences"; @Override public void onCreate(Bundle savedInstanceState) { // ... SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE); // ... } public void mehrPunkte() { punkte = "3"; SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE); points = load.getString("punkte", "0"); test1.setText(points); SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE); save.edit().putString("punkte", punkte).commit(); } 

Also, use constants to indicate the mode, not integer literals (MODE_PRIVATE, not 0)

Sign up to request clarification or add additional context in comments.

Comments

0

Put mehrPunkte(); in onCreate()

2 Comments

look my comment above: the method is called and than it shows "3". But when i restart it shows "0" again
Binyamin Sharet's answer is what you're looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.