Search code examples
javaandroidandroid-fragmentsandroid-activitysharedpreferences

How to transfer String from Fragment to Activity in Android


I'm trying to accomplish the transfer of a string value from a Fragment to an Activity below. The result of the transfer says that the value is empty when transferred to the activity. Please let me know if you need more information.

Fragment:

//put selected chapter title in memory

String selectedChapter = chapters[position];

SharedPreferences pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putString("selectedChapter", selectedChapter);
edt.commit();

//launch activity
Intent intent = new Intent(getActivity(), ChapterDetailActivity.class);
startActivity(intent);

Activity:

   //retrieve selected chapter filename from previous view

    SharedPreferences pref = ChapterDetailActivity.this.getPreferences(0);
    String filename = pref.getString("selectedChapter", "empty");

    Log.e("File: ", filename);

Solution

  • I like to create a helper class for saving preferences. This will access them using a file name, instead of using the context. This means all your prefs are stored in one place, and you can create constants to hold the keys.

    When passing a string literal like "selectedChapter", the compiler has no way of checking if we mis-spelled the value. By creating a constant, the compiler will be able to check that the key exists.

    public class PreferencesHelper {
    
        private SharedPreferences prefs;
    
        private static final String FILE_NAME = "com.yourpackage.yourapp.prefs";
    
        public static final String KEY_CHAPTER = "chapter";
    
        public PreferencesHelper(Context context) {
            prefs = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
        }
    
    
        /**
         * Save the specified value to the shared preferences
         * 
         * @param key
         *            The key of the value you wish to load
         * @param value
         *            The value to store
         */
        public void save(String key, String value) {
            prefs.edit().putString(key, value).commit();
        }
    
    
        /**
         * Load the specified value from the shared preferences
         * 
         * @param key
         *            The key of the value you wish to load
         * @param defValue
         *            The default value to be returned if no value is found
         */
        public int loadString(String key, String defValue) {
            return prefs.getString(key);
        }
    
    }
    

    Then, you activity can access it like so:

    PreferencesHelper prefs= new PreferencesHelper(this);
    

    And your fragments like so:

    PreferencesHelper prefs = new PreferencesHelper(getActivity());
    

    And to access the data:

    // Save
    prefs.save(PreferencesHelper.KEY_CHAPTER, chapter);
    
    // Load
    prefs.load(PreferencesHelper.KEY_CHAPTER, null)