2013-01-12 160 views
2

我有一個小型遊戲,我正在研究,我只是在更新分數,但我無法讓它正常工作。Android SharedPreferences似乎無法正常工作

注意:我剪下了我的程序片斷以顯示在這裏,我有很多其他正在設置的東西,但它們根本不觸及「分數」,這就是爲什麼代碼是小號速記

我的代碼:

public class Start_Test extends Activity { 

TextView total_points; 
long new_total; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_three); 
    total_points = (TextView) findViewById(R.id.points); 
     SharedPreferences pref = getSharedPreferences("Prefs", 
       Context.MODE_PRIVATE); 
     new_total = pref.getLong("total_points", 0); 
     setTouchListener(); 
    updateTotal(0); 


} 

public void updateTotal(long change_in_points) { 
     SharedPreferences pref = getSharedPreferences("Prefs", 
       Context.MODE_PRIVATE); 
     new_total = new_total + change_in_points; 
     pref.edit().putLong("total_points", new_total); 
     pref.edit().commit(); 
     total_points.setText("" + new_total); 

    } 

public void setTouchListeners() { 

     button.setOnTouchListener(new OnTouchListener() { 
      SharedPreferences pref = getSharedPreferences("Prefs", 
        Context.MODE_PRIVATE); 

      @Override 
      public boolean onTouch(View v, MotionEvent event) { 
       updateTotal(25); 
       return false; 
      } 

     }); 
} 

回答

3

我認爲它的,因爲你正在創建一個新的共享偏好編輯實例。 (您撥打.edit()兩次,並提交一個uneditted版)

更改代碼...

SharedPreferences pref = getSharedPreferences("Prefs", 
      Context.MODE_PRIVATE); 
    new_total = new_total + change_in_points; 
    pref.edit().putLong("total_points", new_total); 
    pref.edit().commit(); 

以下幾點:

SharedPreferences.Editor pref = getSharedPreferences("Prefs", 
      Context.MODE_PRIVATE).edit(); 
    new_total = new_total + change_in_points; 
    pref.putLong("total_points", new_total); 
    pref.commit(); 
+1

啊。很簡單。不能相信我做到了。我會重寫所有的「放」陳述。 **編輯:**只是試了一下。有效!謝謝! 6分鐘,直到我可以接受它。嘿嘿。 – EGHDK

+0

@EGHDK:p至少你知道下次:) – Doomsknight

2

每次調用.edit()創建一個新的編輯器。

變化

pref.edit().putLong("total_points", new_total); 
pref.edit().commit(); 

Editor editor = prefs.edit(); 
editor.putLong("total_points", new_total); 
editor.commit(); 
相關問題