1

when testing an activity in my app I see that it's not using the values I've set using the PreferenceActivity.

I can confirm that the values are corretly set in the PrefsActivity (at least "locally"), because every time I open it, the settings are exactly like they were when I closed it the last time...

Do I have to specify in my PreferenceActivity which preference file to store the settings into, or is it a problem with the methods I'm using to import those values for use in my activity? It feels like I've searched all over the web without ever finding a clear answer to that question...

This is where my activity is supposed to load the preferences, does it look right? I know that's the only thing missing, because the calculation works just fine when I run it in debug mode and manually input the values to use...

public void OnStart() {
    // Loads the values for the calculator to use
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       bodymass = settings.getInt(getString(R.string.pref_key_user_mass).toString(), 0);
       gender = settings.getString(getString(R.string.pref_key_user_gender).toString(), "");

Also, does this following code look right to you? (I would also be grateful if someone told me how to make an 'if' statement comparing several variables at once - e.g. if (one out of three fields are empty) {do something})

    //Checks defined user gender and sets value to be used by calc accordingly
    if (gender == "male") {
        genderValue = 0.7;
    }
    else if (gender == "female") {
        genderValue = 0.6;
    }
    else if (gender == "") {
        settingsAlert();
    }

It never seems to trigger the settingsAlert()-function, even when all app data is wiped (it should then spawn an alert message, prompting the user to go set the preferences before using, but nothing happens)

Here's the code that's supposed to spawn the alert:

public void settingsAlert() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("@string/dialog_setPrefs_text")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   Intent gotoSettings = new Intent(ActivityCalc.this, ActivitySettings.class); 
                   startActivity(gotoSettings);
               }
           })
           .setNegativeButton("No", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    finish();
               }
           })
           .create();
}

--UPDATE--

I have now managed to get the alert dialog spawn like it should, I figured I'd post the code lines that made it happen, so others with the same problem can watch and learn... :)

The problem appeared to be that the alert was indeed created correctly, but never actually called to display - therefore everything worked perfectly once I added that little .show() after the .create() in the last line.

Alternatively, you can define it as an AlertDialog object, and just call it whenever you feel like it:

    AlertDialog alert = builder.create();
    alert.show();

I'm posting the contents of my PreferenceActivity class here for you to see

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // This line will import the preferences to display in the settings activity
    addPreferencesFromResource(R.xml.settings);
}

To see how to build the preference resource file, look at this article

I've no longer included the string for specifying the name of the shared prefs to use, as I changed the get-method to use DefaultSharedPreferences instead:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

I have now only defined and initialized the variables required to be persistent for the rest of the activity:

private double genderValue = 0;
private String gender = "";
private int bodymass = 0;

The app now works exactly like it should - not crashing, and correctly loading the preferences as set in the PreferenceActivity.

ToVine
  • 560
  • 5
  • 16

1 Answers1

1

You need to use equals for the IF-ELSE sentences

if (gender.equals("male")) { //equals
    genderValue = 0.7;
}
else if (gender.equalsIgnoreCase("female")) { //Here the equalsIgnorecase one
    genderValue = 0.6;
}
else if (gender == "") {
    settingsAlert();
} else {
    settingsAlert();  //Probably it always comes here.
}

Another thing.. did you saved the preferences correctly with 'commit' ?

  settings.edit().putString(getString(R.string.pref_key_user_gender).toString(), gender).commit();

--After 3rd comment---

Never tried. One for each works fine. But if you check 'duanhong169' comment, there're 2 following putString and the last commited, so.. make a try :) Anyway you can just do:

SharedPreferences.Editor editor = settings.edit();
editor.putString("gender", genderValue);
editor.putInt("bodymass", bodymassValue);
editor.commit();

And answering your other question.. you need the 'edit' to save a prefference, is how it works. you can use it at onpause, onrestart, or just after you've the data you need (inside a method). Ie if you need a login data, once after you checked the login is correct, and if you've a different login-pass value stored (different user), you can edit.putString to save the new value inside onResult confirmation.

The better thing you can do is try different methods of saving to prefferences with different tags and then creare a Log and do getString() from each tag, so you'll know which one works, and then you can choose the better/easier for your case.

-- UPDATE 2 --

As far as I know.. (i've never tried that, and like you, i'm really new in android) your preferences.xml should be placed at res/xml and then:

public class PreferencesFromXml extends PreferenceActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Load the preferences from an XML resource
        addPreferencesFromResource(R.xml.preferences);
    }
}

and to get the data:

PreferenceManager.setDefaultValues(this, R.xml.prefer, false);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this); 
p.getString("key", "value_default")
Jordi
  • 616
  • 2
  • 9
  • 16
  • Do I need to commit changes made in a PreferenceActivity? I thought the framework was supposed to handle all that on its own... (see comment to duanhong169's answer above) – ToVine Apr 23 '12 at 12:29
  • Yes, you need it (you can check http://stackoverflow.com/q/2614719 and another option instead of commit() in http://stackoverflow.com/q/5960678/1140648 ). I think you can access to the data.. check http://stackoverflow.com/q/5951418 – Jordi Apr 23 '12 at 13:41
  • Ok, so I'm guessing I have to make a separate settings.edit() for each preference I want to save and make available to the other activities, am I right? And then, will I have to call commit after each one, or can I just "sum it all up" with one commit at the end? Both edit and commit should be put under either onPause or onStop, or doesn't it matter? – ToVine Apr 23 '12 at 15:55
  • I've updated the question with the contents of my PreferenceActivity - can't really get it to work properly. Would be awesome if you'd take a quick look at it and tell me how it should be. Sorry to bother you this much, I'm really grateful that you're taking the time to help out a newbie to Java/Android - it means a lot! :) – ToVine Apr 23 '12 at 17:48
  • So the second argument in the 'getString()' is the default value to load if no setting is present? And should the get-function be called inside the preferenceActivity, or just in the main activity when I need to pull the data? – ToVine Apr 24 '12 at 13:24
  • Yes, the 2nd argument is a default value. And i don't know about the 2nd question, i've only put-get data in the past, and never loaded from a xml file. You should check it and if you want, explain the results :) – Jordi Apr 24 '12 at 14:13
  • Get function is not needed - everything actually works like intended now, I'll update the original question with the contents of my PreferenceActivity to show others how I did it. Thanks a lot for your help! Please up-vote my question if you feel it's relevant to other "newbies"... :) – ToVine Apr 27 '12 at 15:23