Link to home
Create AccountLog in
Avatar of opike
opike

asked on

Issue reading preferences in android app

I'm trying to use the PreferenceActivity in a java app and I'm able to bring up a screen to modify the preferences but I'm unable to read the preferences in a nother activity in the same App.

I have one xml file under the xml/ folder called default_values.xml that contains just a single preference. I've attached the contents of that file.

 
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android">


    <EditTextPreference
            android:key="json_url_pref"
            android:defaultValue="@string/json_url"
            android:title="@string/title_edittext_preference"
            android:summary="@string/summary_edittext_preference"
            android:dialogTitle="@string/dialog_title_edittext_preference" />


</PreferenceScreen>

Open in new window


This is the code I'm trying to use in my Activity to read the preference:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(EarningsActivity.this);
                    
       
String tmp = sp.getString("json_url_pref","-1");


sp.getString(...) is always returning -1.

I think this is a contextual issue that for some reason this activity does not have access to the application preferences (at least my intention is to have the preferences be visible by all activities in the application).
       
Avatar of garypfirstech
garypfirstech

I'm not sure how you're storing your preferences, but the value of the key is retrieved from the android:name attribute.  However, I don't see that your EditTextPrefernce has the name attribute populated.
 
I've experimented with this a little more and I understand your situation better now.  Please ignore my previous comment. :(

Does your PreferenceActivity subclass onCreate method look like:

  @Override
  public void onCreate(Bundle myBundle)
  {
    super.onCreate(myBundler);
    addPreferencesFromResource(R.xml.default_values);
  }

Open in new window


If it looks like that, things should be working okay and we'll have to look further.  If it doesn't look like that, can you please post what it looks like?
That should be myBundle (not myBundler).  Sorry about that.
SOLUTION
Avatar of opike
opike

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
ASKER CERTIFIED SOLUTION
Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of opike

ASKER

Received help from garypfirstech and also figured out part of the problem on my own.
Avatar of opike

ASKER

Received help from garypfirstech and also found out part of the problem on my own.