2013-07-30 2 views
0

내 앱에 숫자를 추가 할 때 최대 15 개라고 가정 해 봅니다. 다음에 앱을 열 때 충돌이 발생하거나 휴대 전화가 다시 시작되거나 앱이 종료 된 경우에도 문제가 발생하지 않도록하고 싶습니다. 0이 아닌 15에서 계속되어야합니다. 어떻게해야합니까?중단 된 곳에서 계속 하시겠습니까?

나는 이런 식으로 시도했다. 이것은 아마도 그것을 고치는 방법을 모르는 잘못된 것이다.

public class MainActivity extends Activity { 
private int i = 0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Button btn = (Button) findViewById(R.id.but); 
    final TextView txt = (TextView) findViewById(R.id.txt); 

    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this); 
    btn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      SharedPreferences.Editor editor = app_preferences.edit(); 
      i++; 
      txt.setText(" " + i); 
      i++; 
      editor.putInt("Scores: ", i); 
      editor.commit(); 
     } 
    }); 


} 

    } 
+0

[된 SharedPreferences] (http://developer.android.com/reference/android/content/SharedPreferences.html) – TronicZomB

+0

내가 지금까지 시도 한 내용을 참조하십시오. – ivesingh

+0

'putInt' 물건을'onPause' 메소드에 넣으십시오. – TronicZomB

답변

2
public class MainActivity extends Activity { 
private int i = 0; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

      // let i be previously saved value or default to zero 
      i = app_preferences.getInt("Scores: ",0); 

    Button btn = (Button) findViewById(R.id.but); 
    final TextView txt = (TextView) findViewById(R.id.txt); 

    final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this); 
    btn.setOnClickListener(new View.OnClickListener() { 

     @Override 
     public void onClick(View v) { 
      SharedPreferences.Editor editor = app_preferences.edit(); 

      i++; 
      txt.setText(" " + i); 

      //i++; maybe DONT really increment twice (unless thats what you intended) 
      editor.putInt("Scores: ", i); 
      editor.commit(); 
     } 
    }); 


} 

    } 
+0

이 작품! 유일한 문제는 이제 내가 "int"대신 응용 프로그램을 다시 열면 버튼을 클릭 할 때까지 아무것도 보이지 않지만 이전 번호가 표시되도록하려는 것입니다. 당신의 도움을 주셔서 감사합니다. :) – ivesingh

+0

나는 이것을 지금 생각한다. 나는 txt.setText (""+ i);를 배치했다. onClick() 메소드 전에. – ivesingh

관련 문제