Android SharedPreferences不保存文件

时间:2015-07-30 10:56:42

标签: android sharedpreferences

我遇到SharedPreferences问题。我有两个活动:MainActivity和SettingsActivity。当MainActivity正在strating时,在onCreate方法中我默认创建设置并检查或者这是第一次运行应用程序。当我转到SettingsActivity时,我会检查或默认设置是否存在,并尝试从这些设置中设置我的类字段。但是在loadExistSettings()方法中if-statement不执行。

public class MainActivity extends Activity {
public static SharedPreferences defaultSettings;
//----------------------
public  boolean ledOn = false;
//----------------------
ImageButton switcher;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
    switcher = (ImageButton) findViewById(R.id.switcher);
    defaultSettings = getSharedPreferences(SettingsActivity.APP_PREFERENCES, Context.MODE_PRIVATE);
    if(!defaultSettings.getBoolean("hasVisited", false)){
        createDefaultSettings();
        SharedPreferences.Editor editor = defaultSettings.edit();
        editor.putBoolean("hasVisited", true);
        editor.commit();
    }
}

public void switchLED(View view){
    if(!ledOn){
        switcher.setImageResource(R.drawable.imgon);
        ledOn = true;
    }else{
        switcher.setImageResource(R.drawable.imgoff);
        ledOn = false;
    }
}

public void showSettings(View v){
    Intent intent = new Intent(this, SettingsActivity.class);
    startActivity(intent);
}

public void createDefaultSettings(){
    SharedPreferences.Editor editor = defaultSettings.edit();
    editor.putBoolean(SettingsActivity.NORMAL_MODE, true);
    editor.putBoolean(SettingsActivity.VIBRO_MODE, true);
    editor.putBoolean(SettingsActivity.SILENT_MODE, true);
    editor.putBoolean(SettingsActivity.INCOMING_CALL, true);
    editor.putBoolean(SettingsActivity.SMS_INCOME, true);
    editor.putInt(SettingsActivity.BATTERY_SHUTDOWN, 50);
    editor.putInt(SettingsActivity.DELAY_ON, 300);
    editor.putInt(SettingsActivity.DELAY_OFF, 300);
    editor.putInt(SettingsActivity.SMS_REPEAT, 3);
    editor.commit();
} 

}

public class SettingsActivity extends Activity {

public static final String APP_PREFERENCES = "applicationSettings";
public static final String NORMAL_MODE = "workInNormalMode";
public static final String VIBRO_MODE = "workInVibroMode";
public static final String SILENT_MODE = "workInSilentMode";
public static final String INCOMING_CALL = "workWhenIncomingCall";
public static final String SMS_INCOME = "workWhenSMSIncome";
public static final String BATTERY_SHUTDOWN = "battery";
public static final String DELAY_ON = "on";
public static final String DELAY_OFF = "off";
public static final String SMS_REPEAT = "smsRepeat";
public static SharedPreferences appSettings;

public static boolean inNormalMode = true;
public static boolean inVibroMode = true;
public static boolean inSilentMode = true;
public static boolean whenIncomingCall = true;
public static boolean whenSmsIncome = true;
public static int battery = 10;
public static int sleepOn = 300;
public static int sleepOff = 300;
public static int smsRepeat = 3;

CheckBox checkNormalMode;
CheckBox checkVibroMode;
CheckBox checkSilentMode;
CheckBox checkIncomingCall;
CheckBox checkIncomingSms;
TextView percentValue;
SeekBar delayOn;
TextView delayOnValue;
SeekBar delayOff;
TextView delayOffValue;
SeekBar sms;
TextView smsRepeatValue;
Button accept;
Button cancel;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    appSettings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
    checkNormalMode = (CheckBox) findViewById(R.id.checkBox1);
    checkVibroMode = (CheckBox) findViewById(R.id.checkBox2);
    checkSilentMode = (CheckBox) findViewById(R.id.checkBox3);
    checkIncomingCall = (CheckBox) findViewById(R.id.checkBox4);
    checkIncomingSms = (CheckBox) findViewById(R.id.checkBox1);
    percentValue = (TextView)findViewById(R.id.textView15);
    delayOn = (SeekBar) findViewById(R.id.seekBar);
    delayOn.incrementProgressBy(100);
    delayOn.setMax(2000);
    delayOnValue = (TextView)findViewById(R.id.textView16);
    delayOff = (SeekBar) findViewById(R.id.seekBar2);
    delayOff.incrementProgressBy(100);
    delayOff.setMax(2000);
    delayOffValue = (TextView) findViewById(R.id.textView17);
    sms = (SeekBar) findViewById(R.id.seekBar3);
    sms.incrementProgressBy(1);
    sms.setMax(5);
    smsRepeatValue = (TextView) findViewById(R.id.textView18);
    accept = (Button) findViewById(R.id.button);
    cancel = (Button) findViewById(R.id.button2);

    loadExistSettings();

    //Отримати мінімальне допустиме значення батареї
    percentValue.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SettingsActivity.this);
            builder.setTitle("Мінімальний заряд батареї");
            final EditText input = new EditText(SettingsActivity.this);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            builder.setView(input);
            builder.setNegativeButton("Відміна", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setPositiveButton("ОК", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    battery = Integer.parseInt(input.getText().toString());
                    percentValue.setText(String.valueOf(battery).toCharArray(), 0, String.valueOf(battery).toCharArray().length);
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    });

    //Отримати час скільки спалах має бути увімкнений
    delayOn.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            sleepOn = progress;
            delayOnValue.setText(String.valueOf(sleepOn).toCharArray(), 0, String.valueOf(sleepOn).toCharArray().length);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    //Отримати час скільки спалах має бути вимкнений
    delayOff.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            sleepOff = progress;
            delayOffValue.setText(String.valueOf(sleepOff).toCharArray(), 0, String.valueOf(sleepOff).toCharArray().length);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    //Отримати кількість повторень при вхідних смс
    sms.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            smsRepeat = progress;
            smsRepeatValue.setText(String.valueOf(smsRepeat).toCharArray(), 0, String.valueOf(smsRepeat).toCharArray().length);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {

        }
    });

    //Прийняти налаштування
    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(checkNormalMode.isChecked()) { inNormalMode = true; } else { inNormalMode = false; }
            if(checkVibroMode.isChecked()) { inVibroMode = true; } else { inVibroMode = false; }
            if(checkSilentMode.isChecked()) { inSilentMode = true; } else { inSilentMode = false; }
            if(checkIncomingCall.isChecked()) { whenIncomingCall = true; } else { whenIncomingCall = false; }
            if(checkIncomingSms.isChecked()) { whenSmsIncome = true; } else { whenSmsIncome = false; }
            createPreferences();
        }
    });

    //Відхилити налаштування
    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            loadExistSettings();
        }
    });
}

public void createPreferences(){
    SharedPreferences.Editor editor = appSettings.edit();
    editor.putBoolean(NORMAL_MODE, inNormalMode);
    editor.putBoolean(VIBRO_MODE, inVibroMode);
    editor.putBoolean(SILENT_MODE, inSilentMode);
    editor.putBoolean(INCOMING_CALL, whenIncomingCall);
    editor.putBoolean(SMS_INCOME, whenSmsIncome);
    editor.putInt(BATTERY_SHUTDOWN, battery);
    editor.putInt(DELAY_ON, sleepOn);
    editor.putInt(DELAY_OFF, sleepOff);
    editor.putInt(SMS_REPEAT, smsRepeat);
    editor.commit();
}

public void loadExistSettings(){
    if(appSettings.contains(APP_PREFERENCES)){
        inNormalMode = appSettings.getBoolean(NORMAL_MODE, true);
        checkNormalMode.setChecked(inNormalMode);
        inVibroMode = appSettings.getBoolean(VIBRO_MODE, true);
        checkVibroMode.setChecked(inVibroMode);
        inSilentMode = appSettings.getBoolean(SILENT_MODE, true);
        checkSilentMode.setChecked(inSilentMode);
        whenIncomingCall = appSettings.getBoolean(INCOMING_CALL, true);
        checkIncomingCall.setChecked(whenIncomingCall);
        whenSmsIncome = appSettings.getBoolean(SMS_INCOME, true);
        checkIncomingSms.setChecked(whenSmsIncome);
        battery = appSettings.getInt(BATTERY_SHUTDOWN, 20);
        percentValue.setText(String.valueOf(battery).toCharArray(), 0, String.valueOf(battery).toCharArray().length);
        sleepOn = appSettings.getInt(DELAY_ON, 300);
        delayOnValue.setText(String.valueOf(sleepOn).toCharArray(), 0, String.valueOf(sleepOn).toCharArray().length);
        sleepOff = appSettings.getInt(DELAY_OFF, 300);
        delayOffValue.setText(String.valueOf(sleepOff).toCharArray(), 0, String.valueOf(sleepOff).toCharArray().length);
        smsRepeat = appSettings.getInt(SMS_REPEAT, 3);
        smsRepeatValue.setText(String.valueOf(smsRepeat).toCharArray(), 0, String.valueOf(smsRepeat).toCharArray().length);
    }
}

}

1 个答案:

答案 0 :(得分:0)

下面:

if(appSettings.contains(APP_PREFERENCES)){
  ///.....you code here
}

if条件始终为false,因为APP_PREFERENCES是首选项名称,而不是appSettings首选项中可用的键名。

要正确使用SharedPreferences.contains,请在访问以下值之前使用密钥名称检查当前SharedPreferences中是否存在密钥:

if(appSettings.contains(NORMAL_MODE)){
      inNormalMode = appSettings.getBoolean(NORMAL_MODE, true);
      checkNormalMode.setChecked(inNormalMode);
   }