Search code examples
androidandroid-fragmentsandroid-activitysharedpreferencesandroid-tablayout

SharedPreferences Across Multiple Activities Returns NULL


I have shared prefs to be used throughout my app but right now only four activities. The first activity is a recyclerview with checkboxes and the checked status is saved (in the recycler adapter) for each checkbox using a shared prefs helper class. The next activity is then launched as a tablayout with fragments containing a list of random items.

When the user clicks any of these items in the second activity's fragment, a third activity is launched. Here, I try to retrieve the values from the shared prefs helper class but it returns null, same situation in fourth activity too. Also, when I back press twice to first activity, it also returns null.

I would post my code for all activities but that would just make the question lengthy. Here's my helper class:

public class WalpyPrefsHelper {

public Context context;
public SharedPreferences customizePrefs, tabsCountPrefs;
public SharedPreferences.Editor editor, tabsEditor;

public static final String CUSTOMIZE_TABS_PREFS = "customizeTabsPrefs";
public static final String COUNT_TABS_PREFS = "countTabsPrefs";

public static final String KEY_NATURE = "nature";
public static final String KEY_SPACE = "space";
public static final String KEY_SEASONS = "seasons";
public static final String KEY_ART = "art";
public static final String KEY_SCIFI = "sci_fi";
public static final String KEY_MISC = "misc";

public static final String KEY_COUNT = "count_tabs";

public WalpyPrefsHelper(Context context) {
    this.context = context;
    customizePrefs = context.getSharedPreferences(CUSTOMIZE_TABS_PREFS, Context.MODE_PRIVATE);
    editor = customizePrefs.edit();

    tabsCountPrefs = context.getSharedPreferences(COUNT_TABS_PREFS, Context.MODE_PRIVATE);
    tabsEditor = tabsCountPrefs.edit();

}

public void saveNaturePrefs(String s){
    editor.putString(KEY_NATURE, s).apply();
}

public String getKeyNature(){
    return customizePrefs.getString(KEY_NATURE, null);
}

public void removeNaturePrefs(){
    editor.remove(KEY_NATURE).apply();
}

public void saveSpacePrefs(String s){
    editor.putString(KEY_SPACE, s).apply();
}

public String getKeySpace(){
    return customizePrefs.getString(KEY_SPACE, null);
}

public void removeSpacePrefs(){
    editor.remove(KEY_SPACE).apply();
}

public void saveSeasonsPrefs(String s){
    editor.putString(KEY_SEASONS, s).apply();
}

public String getKeySeasons(){
    return customizePrefs.getString(KEY_SEASONS, null);
}

public void removeSeasonPrefs(){
    editor.remove(KEY_SEASONS).apply();
}

public void saveArtPrefs(String s){
    editor.putString(KEY_ART, s).apply();
}

public String getKeyArt(){
    return customizePrefs.getString(KEY_ART, null);
}

public void removeArtPrefs(){
    editor.remove(KEY_ART).apply();
}

public void saveSci_FiPrefs(String s){
    editor.putString(KEY_SCIFI, s).apply();
}

public String getKeyScifi(){
    return customizePrefs.getString(KEY_SCIFI, null);
}

public void removeSci_FiPrefs(){
    editor.remove(KEY_SCIFI).apply();
}

public void saveMiscPrefs(String s){
    editor.putString(KEY_MISC, s).apply();
}

public String getKeyMisc(){
    return customizePrefs.getString(KEY_MISC, null);
}

public void removeMiscPrefs(){
    editor.remove(KEY_MISC).apply();
}

public void removeAllPrefs(){
    editor.remove(KEY_NATURE).apply();
    editor.remove(KEY_SPACE).apply();
    editor.remove(KEY_SEASONS).apply();
    editor.remove(KEY_ART).apply();
    editor.remove(KEY_SCIFI).apply();
    editor.remove(KEY_MISC).apply();
}

public void saveCount(int count) {
    tabsEditor.putInt(KEY_COUNT, count).apply();
}

public int getSaveCount(){
    return tabsCountPrefs.getInt(KEY_COUNT, 0);
}
}

The preferences are saved in first activity recycler adapter like below snippet:

viewholder.customizeSelImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String nature, space, seasons, art, scifi, misc;
            switch (position) {
                case 0:
                    nature = prefsHelper.getKeyNature();
                    if (viewholder.customiseCheckBox.isChecked()) {
                        viewholder.customiseCheckBox.setChecked(false);
                        viewholder.customiseCheckBox.setVisibility(View.INVISIBLE);
                        if (nature != null) {
                            prefsHelper.removeNaturePrefs(); // infer nullity
                            if (count > 0) {
                                count--;
                                Log.d(TAG, "Count Value:\t" + count);
                            }
                            Log.d(TAG, "Position:\t" + position + " is UNChecked");
                        }
                    } else {
                        viewholder.customiseCheckBox.setChecked(true);
                        viewholder.customiseCheckBox.setVisibility(View.VISIBLE);
                        count ++;
                        Log.d(TAG, "Count Value:\t" + count);
                        prefsHelper.saveNaturePrefs(Constants.NATURE); // save value. Works fine
                        Log.d(TAG, "Position:\t" + position + " is Checked");
                    }
                    break;

In next activity, I am able to retrieve the shared prefs values like below snippet:

    String space = prefsHelper.getKeySpace();
    String nature = prefsHelper.getKeyNature();
    String seasons = prefsHelper.getKeySeasons();
    String art = prefsHelper.getKeyArt();
    String scifi = prefsHelper.getKeyScifi();
    String misc = prefsHelper.getKeyMisc();

after initializing like this: prefsHelper = new WalpyPrefsHelper(this); but in third and fourth activities, those strings above return null values.

----Edited Part--- Second Activity Where Prefs Are Used:

public void setUpTabs() {

    prefsHelper = new WalpyPrefsHelper(this);
    int count = prefsHelper.getSaveCount();
    Log.d(TAG, "Tabs Count:\t" + count);

    setUpViewPager(viewPager);
    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    tabLayout.setupWithViewPager(viewPager);
}

private void setUpViewPager(ViewPager viewPager) {

    space = prefsHelper.getKeySpace();
    nature = prefsHelper.getKeyNature();
    seasons = prefsHelper.getKeySeasons();
    art = prefsHelper.getKeyArt();
    scifi = prefsHelper.getKeyScifi();
    misc = prefsHelper.getKeyMisc();

    pagerAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this);
    pagerAdapter.addTab(new Top30Fragment(), Constants.Top30);

    if (nature != null) {
        pagerAdapter.addTab(new NatureFragment(), Constants.NATURE);
    }

    if(space != null){
        pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
    }

    if (seasons != null){
        pagerAdapter.addTab(new SeasonsFragment(), Constants.SEASONS);
    }

    if (art != null){
        pagerAdapter.addTab(new ArtFragment(), Constants.ART);
    }

    if (scifi != null){
        pagerAdapter.addTab(new SciFiFragment(), Constants.SCI_FI);
    }

    if (misc != null){
        pagerAdapter.addTab(new MiscFragment(), Constants.MISC);
    }

    pagerAdapter.addTabAtLastPosition(new PrefsFragment(), Constants.PREFS);

    viewPager.setAdapter(pagerAdapter);
}

I have used shared prefs to set the tablayout at app install time but after navigating other activities and back to this, those tabs from prefs are removed, in other scenarios, my last tab then contains the view and data of the nature fragment from prefs.

In adapter and last two activities in sequence, I am getting the key like this but it returns null:

    prefsHelper = new WalpyPrefsHelper(this);
    Log.d(TAG, "Nature Key:\t" + prefsHelper.getKeyNature());

Also, in the adapter, the value returns null and in other subsequent activities after the second activity. Is this sharedprefs behavior, I have misconfigured somewhere or sharedprefs can't be passed from activity to fragment and adapter context?

I have tried .apply() and .commit() for the editor but same situation occurs. Anyone understands why? Thanks.


Solution

  • I have fixed this problem by using sqlite to persist and retrieve the values.