开发者

get and set listPreference from another activity not working

I'm trying to get and set a listPreference value from different activities and it's not working.

When I read and write it from my main activity, it only keeps whatever I write, so I'm assuming that I'm not targeting the listPreference correctly when I'm out of the activity because it's working inside my preference activity no problem.

I've seen some references on the developer website to CharSequence with getValue and getEntryValues but I haven't had luck getting them to work correc开发者_开发技巧tly either.

Here is my code for clicking a button and setting the listpreference value then it launches an intent to switch activities:

Main Activity, attempting to set the value of the listpreference to the first index value;

        SharedPreferences settings = getSharedPreferences("PreferenceXML", 
                MODE_PRIVATE);
            SharedPreferences.Editor editor = settings.edit();

            editor.putString("ListPreferenceInXML", "1");
            editor.commit();

            String levelCheck = settings.getString("ListPreferenceInXML","1");

In my next activity I call read the value on launch to see which listPreference is active and it is always the number I write from the mains activity listed above. The problem is when I goto the actual Preference activity and it doesn't match or update when I change it on the ListPreference and launch the same activity from there (it still reads the value I set from the Main activity button)

code as follows for activity trying to read ListPreference:

    SharedPreferences settings = getSharedPreferences("PreferenceXML", 
                MODE_PRIVATE);

    Toast.makeText(this, settings.getString("ListPreferenceInXML","1"), 1000).show();


So I finally figured it out, the problem was with the way I was calling the preferences. Instead of calling the preferences like this, in both cases;

   SharedPreferences settings = getSharedPreferences("PreferenceXML", 
            MODE_PRIVATE);

Call them like this:

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

I'm not sure if there is a step missing out of the first way of calling the preferences but this 2nd way worked like a champ.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜