2014-09-12 3 views
0

공유 환경 설정에 부울 값을 저장하려고합니다. 그런 다음 부울 값을 문자열로 변환하고 textview를 채 웁니다. 이 코드는 잘 작동합니다. 하지만 에뮬레이터에서 앱을 제거하면 부울 값이 손실됩니다. 그래서 부울을 저장하는 것이 올바른 방법인지 알고 싶습니다.sharedpreferences에 부울을 저장하는 올바른 방법입니까?

public class MainActivity extends Activity implements OnClickListener { 
public TextView bool; 
public boolean enabled; 
public Button button; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     SharedPreferences prefs = this.getSharedPreferences(
        "com.example.app", Context.MODE_PRIVATE); 
     boolean enabled = prefs.getBoolean("key", false); 

     TextView bool = (TextView) findViewById(R.id.bool); 
     String theValueAsString = new Boolean(enabled).toString(); 
     bool.setText(theValueAsString); 

     Button button = (Button) findViewById(R.id.button1); 
     button.setOnClickListener(this); 

    } 

    @Override 
    public void onClick(View v) { 
     // TODO Auto-generated method stub 
     changeBoolean(); 
     SharedPreferences prefs = this.getSharedPreferences(
        "com.example.app", Context.MODE_PRIVATE); 
     boolean enabled = prefs.getBoolean("key", false); 
     TextView bool = (TextView) findViewById(R.id.bool); 
     String theValueAsString = new Boolean(enabled).toString(); 
     bool.setText(theValueAsString); 

    } 

    public boolean changeBoolean(){ 
     SharedPreferences prefs = this.getSharedPreferences(
        "com.example.app", Context.MODE_PRIVATE); 
     enabled = true; 
     prefs.edit().putBoolean("key",enabled).commit(); 
     return enabled; 

    } 

} 

감사합니다.

  1. 부울을 sharedpreferences에 저장하는 올바른 방법입니까?

  2. 응용 프로그램을 다시 설치하면 데이터가 손실됩니다. 올바른가요? (거짓 "키")

    부울 = prefs.getBoolean 활성화;

  3. 나는이 줄을 unterstand하지 않습니다

왜 거짓입니까? sharedpreferences에 저장할 때 자동으로 변경됩니까?

+0

SharedPreferences는 응용 프로그램에만 "샌드 박스"에서 작동합니다. 응용 프로그램을 삭제/제거하면이 샌드 박스에 저장된 모든 데이터가 삭제됩니다. –

+0

감사합니다. 업데이트를 업로드하면 어떻게됩니까? 업데이트가 안전한가요? – basti12354

+0

예. 응용 프로그램을 업데이트해도 문제가 없습니다. –

답변

1

이 된 SharedPreferences하는 부울을 저장하는 올바른 방법인가를? 당신은 항상 값 true 아니라 "변화"값을 저장 changeBoolean()을하려는 경우

이, 작동합니다.

응용 프로그램을 다시 설치하면 데이터가 손실됩니다. 올바른가요?

다시 설치하면 앱 데이터가 유지됩니다. 앱의 데이터를 삭제하거나 명시 적으로 선택하면 공유 환경 설정도 손실됩니다.

내가이 줄 unterstand하지 않는

:

boolean enabled = prefs.getBoolean("key", false); 

왜 거짓이를? sharedpreferences에 저장할 때 자동으로 변경됩니까?

두 번째 매개 변수가 기본값입니다. getBoolean()은 공유 된 환경 설정에 "key"에 저장된 값이없는 경우이를 반환합니다.

0

당신은 설정하려면 다음 코드를 사용할 수있는 부울

SharedPreferences.Editor editor = context.getSharedPreferences(you_pref_name, Context.MODE_PRIVATE).edit(); 
    editor.putBoolean(YOUR_KEY, you_boolean_value); 
    editor.commit(); 

부울 사용 얻을 :

SharedPreferences preferences = context.getSharedPreferences(you_pref_name, Context.MODE_PRIVATE); 
     return preferences.getBoolean(YOUR_KEY, false); 
관련 문제