简体   繁体   中英

Trying to only run code if a variable has been set to false

So I'm using Android's SharedPreferences to save and load the colour the user has chosen, however without a check to see if the preference "initial" is false, navigating to the SettingsActivity crashes the app as it can't load a preference of colour because one hasn't set. Now, I've stopped this from crashing by using the "initial" preference (meaning has the preference colour been stored yet) but now the preference of colour is not being saved. I should mention colour is chosen my radio button group.

Here is my Settings Activity:

public class SettingsActivity extends Activity {

RadioGroup colourPicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // requesting to turn the title OFF
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    // making it full screen
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    // set layout file for this activity
    setContentView(R.layout.settings);
    // lock orientation to portrait
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // radio group id
    colourPicker = (RadioGroup) findViewById(R.id.colourPicker);

    // listeners
    colourPicker.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            switch (checkedId) {
            case R.id.radioOrange:
                save("orange");
                Log.d("colour", "saving orange");
                break;
            case R.id.radioLilac:
                save("lilac");
                Log.d("colour", "saving lilac");
                break;
            case R.id.radioRed:
                save("red");
                Log.d("colour", "saving red");
                break;
            case R.id.radioTeal:
                save("teal");
                Log.d("colour", "saving teal");
                break;
            }
        }

    });
}

@Override
public void onResume() {
    super.onResume();
    SharedPreferences sharedPreferences = getSharedPreferences("initial", 0);
    if (sharedPreferences.getBoolean("initial", false)) {
        colourPicker.check(R.id.radioOrange);
        sharedPreferences = getSharedPreferences("colour", 0);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("initial", true);
        editor.commit();
    } else {
        load();
    }
}

// save colour choice
private void save(final String colour) {
    SharedPreferences sharedPreferences = getSharedPreferences("colour", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString("colour", colour);
    editor.commit();
}

// load colour choice
private void load() {
    SharedPreferences sharedPreferences = getSharedPreferences("colour", 0);
    if (sharedPreferences.getString("colour", null).equals("orange")) {
        colourPicker.check(R.id.radioOrange);
    } else if (sharedPreferences.getString("colour", null).equals("lilac")) {
        colourPicker.check(R.id.radioLilac);
    } else if (sharedPreferences.getString("colour", null).equals("red")) {
        colourPicker.check(R.id.radioRed);
    } else {
        colourPicker.check(R.id.radioTeal);
    }
}

@Override
public void onBackPressed() {
    Intent mainScreenActivityIntent = new Intent(SettingsActivity.this, MainScreenActivity.class);
    startActivity(mainScreenActivityIntent);
    finish();
}

}

I'm running this method in the MainActivity:

public void runBefore() {
    SharedPreferences sharedPreferences = getSharedPreferences("initial", 0);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("initial", false);
    editor.commit();
}

Now as I mentioned, the colour isn't being saved when you close or press back out of the Settings Activity, if anyone knows a work around or could help me change the code so this works without the crash, this would be a great help!

I don't believe you actually need the "initial" preferences. The reason your app used to crash was most likely because of the use of the null default in:

if (sharedPreferences.getString("colour", null).equals("orange"))

If there is no preference, the equals() method is called on a null string which is a null pointer exception. Instead, check if it == null first. If so, set your default, otherwise you can carry on checking it with equals().

private void load() {
    SharedPreferences sharedPreferences = getSharedPreferences("colour", 0);
    String colour = sharedPreferences.getString("colour", null);

    if (colour == null)
        colourPicker.check(R.id.radioOrange);  //Default if no preference exists
    else if (colour.equals("orange")) {
        colourPicker.check(R.id.radioOrange);
    } else if (colour.equals("lilac")) {
        colourPicker.check(R.id.radioLilac);
    } else if (colour.equals("red")) {
        colourPicker.check(R.id.radioRed);
    } else {
        colourPicker.check(R.id.radioTeal);
    }
}

the problem is in the below line

if (sharedPreferences.getBoolean("initial", false)) 

for the first time you want to execute the first block .. but look in first time the sharedpreferences will return false and this will not be executed.

you have two options

  1. if (!sharedPreferences.getBoolean("initial", false)) or
  2. make the default intial to true .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM