2013-01-12 2 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

아로 변경

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

. 아주 간단합니다. 내가 그랬다는 것을 믿을 수 없다. 모든 "put"문장을 다시 작성하겠습니다. ** 편집 : ** 방금 해봤습니다. 그것은 효과가있다! 감사! 내가 받아 들일 때까지 6 분. ㅎ. – EGHDK

+0

@EGHDK : p 적어도 다음에 알거야 :) – Doomsknight

2

각 호출이 .edit하기() 새 편집기를 만듭니다.

Editor editor = prefs.edit(); 
editor.putLong("total_points", new_total); 
editor.commit(); 
관련 문제