Search code examples
androidsharedpreferencespreferenceactivity

Android - How to set a preference from within another Activity


I have a PreferenceActivity class that handles the getting and setting of preferences within my application. But I have a "main" Activity class that makes a call to a web service right at start-up, and based on the return value from the web service, needs to update one of the preferences.

I can't seem to get this to work without throwing a NullPointerException error.

Here is the code from the main Activity:

protected void onPostCreate(Bundle savedInstanceState)
{

    if(getWebServiceResult.equals("FALSE"))
    {
      //do stuff
    }
    else
    {
       myPreferences prefs = new myPreferences();               
       prefs.updateMyChoice("TRUE");
    }
}

And here is the code from the PreferenceActivity class that is throwing the error:

public void updateMyChoice(String newText)
{
    if(subscriber_opt_in == null) //this is coming up null
    {
       subscriber_opt_in = (EditTextPreference) findPreference("opt_in"); //error here
    }
   subscriber_opt_in.setText(newText);
   subscriber_opt_in.setSummary(newText);
}

I need to know how to properly update this preference. If there's a way to do it within the main Activity class, that's even better, but if I have to do it through the PreferenceActivity class, I just need to understand how to do it.

Thanks!


Solution

  • You should use SharedPreference class: http://developer.android.com/reference/android/content/Context.html#getSharedPreferences%28java.lang.String,%20int%29

    Code examples and use here: http://developer.android.com/guide/topics/data/data-storage.html#pref