0

I am having an issue with SharedPreferences that is kind of weird.

I have an Activity that holds a Fragment in a ViewPager. The fragment shows an icon and text. You can change the icon (check mark or cross, check mark is default) and text displayed in this fragment from another activity.

Now I want to save the text and chosen icon, so the fragment is shown with the same text and icon, even when you close the app and restart it later.

So I tried to achieve this with SharedPreferences, but when I tried it, my fragment showed me no text though I have default values set and the icon is always the cross, no matter what it was before and though the default icon should be the check mark.

I am saving the values in onActivityCreated() of my Fragment when it is created with the data the user inputted in the activity before.

Saving:

SharedPreferences sharedPref = getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();

//Here I am getting the values I want to save from a bundle, city and country...

editor.putString("savedCity", city);
editor.putString("savedCountry", country);
editor.putString("fragmentSaved", "yes");

editor.apply(); 

Then, I am getting the values in onCreate() of my Activity that holds the Fragment:

    SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();

//adding fragment that was created with user input

String ifAdded = sharedPref.getString("addedFragment", "no");

    if(ifAdded.equalsIgnoreCase("yes")){
        Bundle extras = getIntent().getExtras();

        StatusFragment newFragment = new StatusFragment();
        newFragment.setArguments(extras);

        mSectionsPagerAdapter.addFragment(newFragment, extras.getString("city"));

        editor.putString("addedFragment", "no");

        editor.apply();
    }

    //Adding a saved fragment after restart

    String storedSave = sharedPref.getString("fragmentSaved", "no");

    if (storedSave.equalsIgnoreCase("yes")){
        String storedCity = sharedPref.getString("savedCity", "somecity");
        String storedCountry = sharedPref.getString("savedCountry", "somecountry");

        Bundle saves = new Bundle();

        StatusFragment savedFragment = new StatusFragment();

        saves.putString("city", storedCity);
        saves.putString("country", storedCity);

        savedFragment.setArguments(saves);

        mSectionsPagerAdapter.addFragment(savedFragment, saves.getString("city"));
    }

In the activity where the fragments data is created, I have this:

SharedPreferences sharedPref = getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPref.edit();

                    editor.putString("addedFragment", "yes");

                    editor.apply();

                    fragmentHolder.putExtras(bundle);
                    startActivity(fragmentHolder);

bundle has the values the user typed in, and fragmentHolder is the activity that holds the fragment.

I searched for answers in different questions here on stackoverflow, but none of them worked for me, like:

Cannot get value from sharedpreferences

Shared Preferences get lost after shutting down device or killing the app

Shared Preferences reset data when app is force closed or device is restarted

SharedPreferences return only default value

SharedPreferences return only default value

Shared preference always taking default value

SharedPreferences keep getting default value

Sorry if I it is perhaps something trivial, but I haven't worked with Fragments much and I am using SharedPreferences the first time now.

I would be grateful for every helpful answer.

Community
  • 1
  • 1
boehmP
  • 91
  • 1
  • 1
  • 11
  • where you are retrieving the sharedpreference value ??? I cannot see any code for that – Janki Gadhiya Sep 01 '16 at 11:19
  • what is this condition supposed to do? `if(getResources().getString(R.string.pref_fragment_saved).equals("Yes")){` you know it will always be either `true` or `false` based on the value of `R.string.pref_fragment_saved` at `/values/strings.xml` which is not changable during runtime. – Yazan Sep 01 '16 at 11:23
  • How we can access Shared prefernces like this is in your code?`SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);` – Anil Ravsaheb Ghodake Sep 01 '16 at 11:38
  • I think there are two methods I knows which gives Shared Prefernce access `1.PreferenceManager.getDefaultSharedPreferences(this); 2.context.getSharedPrefernces(PREF_NAME,MODE)` – Anil Ravsaheb Ghodake Sep 01 '16 at 11:41
  • @Anil Learn how to look up things in the [android dev docs](https://developer.android.com/reference/android/app/Activity.html#getPreferences(int)), it's quite handy. – adnan_e Sep 01 '16 at 11:43
  • Oh! Sorry guys,I don't know we can access prefernces like this – Anil Ravsaheb Ghodake Sep 01 '16 at 11:48
  • Stop posting duplicate questions. Thank you. – Phantômaxx Sep 13 '16 at 08:14

3 Answers3

1

The problem is solved now. I had to use getActivity().getApplicationContext().getSharedPreferences("com.fragmentdata.myapp", Activity.MODE_PRIVATE); and some of my variables in the bundles and preferences got mixed up. I corrected this and now it works fine :) Thanks for your answers.

boehmP
  • 91
  • 1
  • 1
  • 11
0

You are mixing up things that are stored in your SharedPreference and inside your applications resources (strings.xml)

editor.putString(getString(R.string.pref_fragment_saved), "Yes");

This line saves the string inside your preference XML, but then you try to read it as

getResources().getString(R.string.pref_fragment_saved).equals("Yes")

Which actually just reads the value R.string.pref_fragment_save from your strings.xml

The correct way of reading what you saved would be

getActivity().getPreferences(Context.MODE_PRIVATE).getString(getResources().getString(R.string.pref_fragment_saved), "defaultValue")

Or a bit cleaner:

SharedPreferences prefs = getActivity().getPreferences(Context.MODE_PRIVATE);
String key_frag_saved = getResources().getString(R.string.pref_fragment_saved);

String storedString = prefs.getString(key_frag_saved, "defValue");

if ( storedString.equalsIgnoreCase("yes") ) {...}

And the same way you would read the other saved values from your SharedPreference object instance.

adnan_e
  • 1,764
  • 2
  • 16
  • 25
  • Seems like something is wrong again :/ I get a Fragment with only default values. I updated my question with my new code. – boehmP Sep 01 '16 at 14:17
  • @boehmP If I read correctly, you are reading the values in `onCreate()` of the Activity, which holds the fragment that saves the information? Did you relaunch the activity to see if the information was loaded? And are you certain that `onCreate` got called again? Add Log.i messages for loading and saving and check the order it is executed. – adnan_e Sep 01 '16 at 15:12
  • When I add the fragment I get the following Log outputs: I/Loading: Fragment loaded, I/Saving: Fragment saved, I/Saving: Fragment saved. It saves it twice for some reason and when I close the app and restart it, it has the same output but I have no text and the cross icon, though I have default values. I have absolutely no idea why everything is skipped? – boehmP Sep 03 '16 at 17:22
-1

You wanted to use this

SharedPreferences sharedPref = ...;
extras.putString("city", sharedPref.getString(getResources().getString(R.string.pref_saved_city), ""));

in your onCreate method

injecteer
  • 20,038
  • 4
  • 45
  • 89