0

I am learning how to use shared preferences and I understand how to set it and get it with one class. However I want to be ale to use shared preferences across two classes. Let me explain.

So in the class below I am basically getting the total number of click counts for whenever the jokes, poems or funny stories button is clicked. This code is below (known as MainActivity):

public class MainActivity extends AppCompatActivity{

    final Context context = this;
    int clicksCount = 0;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button jokesButton = findViewById(R.id.button_jokes);
        Button poemsButton = findViewById(R.id.button_poems);
        Button funnyStoriesButton = findViewById(R.id.button_funny_stories);


        jokesButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clicksCount++;
                storeClicks(clicksCount);
                openContentPage("jokes");
            }
        });

        poemsButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clicksCount++;
                storeClicks(clicksCount);
                openContentPage("poems");
            }
        });

        funnyStoriesButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clicksCount++;
                storeClicks(clicksCount);
                openContentPage("funnystories");
            }
        });



    }

    private void openContentPage(String v) {
            Intent intentContentPage = new Intent(MainActivity.this, Content.class);
            intentContentPage.putExtra("keyPage", v);
            startActivity(intentContentPage);

    }

    public void storeClicks(int count)
    {
        SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
        SharedPreferences.Editor meditor = mSharedPreferences.edit();
        meditor.putInt("numberOfClicks", count);
        meditor.apply();
    }

    public int getNumberOfClicks(){
        SharedPreferences mSharedPreferences = getSharedPreferences("numberOfClicks", MODE_PRIVATE);
        int clicksNumber = mSharedPreferences.getInt("numberOfClicks", clicksCount);
        return clicksNumber;
    }


}

However I have another class known as 'Content' and basically this contains a button known as 'Select Another'. I want this to be included with the click count as well.

So that's the goal basically, no matter what page I am on it should keep track of the number of clicks combined for buttons jokes, poems, funny stories and select another. How can this be implemented?

Below is the code for Content:

public class Content extends AppCompatActivity{

    Button selectAnotherButton;
    TextView contentText;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_content);

             selectAnotherButton = findViewById(R.id.button_select_another);


            selectAnotherButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                        setContent();
                    }
            });

    }
mmkp
  • 145
  • 2
  • 16
  • maybe just having a method that updates (commits) and also one more to get the value out the pref editor! and getting them using object of the class in any class would do just fine and private pref and editor are global(static) in nature behind the scene – Rizwan Atta Jun 14 '18 at 11:40

2 Answers2

2

You can use Singleton pattern to implement global access to the SharedPreferences. Something like this:

    public class SharedPreferencesManager {

    private static final String APP_PREFS = "AppPrefsFile";
    private static final String KEY_FOR_SOMETHING = "KEY_FOR_SOMETHING";

    private SharedPreferences sharedPrefs;
    private static SharedPreferencesManager instance;



    private SharedPreferencesManager(Context context) {
        sharedPrefs =
                context.getApplicationContext().getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE);
    }


    public static synchronized SharedPreferencesManager getInstance(Context context){
        if(instance == null)
            instance = new SharedPreferencesManager(context);

        return instance;
    }

    public void setSomething(String something) {
        SharedPreferences.Editor editor = sharedPrefs.edit();
        editor.putString(KEY_FOR_SOMETHING, something);
        editor.apply();
    }

    public String getSomeKey() {
        String someValue = sharedPrefs.getString(KEY_FOR_SOMETHING, null);
        return someValue;
    }
}

You can have as much as you want methods for getting and setting various values to the SharedPreferences, and it will be accessible through the whole application, just do:

SharedPreferencesManager.getInstance(context).getSomeKey();
RadoVidjen
  • 432
  • 7
  • 17
  • Can you show me how it is implemented in both the MAinActivity and COntent classes please as I have included your class and the only thing I'm confused with is the click count within Main Activity and Content – mmkp Jun 14 '18 at 12:32
  • @mmkp Hmm if i get you right, you can save number of clicks from MainActivity like `SharedPreferencesManager.getInstance(context).saveNumberOfClicks(numberofClick);`. Now in some other screen, when you need number of clicks just call `SharedPreferencesManager.getInstance(context).getNumberOfClicks()` and you are good to go. Of course, you need to implement those methods, like i showed you in the answer. If this answer can help, please mark it as right one :) – RadoVidjen Jun 14 '18 at 13:02
1

Shared Preference is just a common file that contains a set of Key Value Pairs.It would be accessible in any class from your App.

For your case , you can store it as a key value pair in one Class . Then retrieve it using the same KeyName in another Class.It should retrieve the value you stored in the other class provided the flow is continous.

Please refer below existing stackoverflow answers for more info :: Android Shared preferences example

Official Docs : https://developer.android.com/training/data-storage/shared-preferences

Tutorial Example : https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

1nullpointer
  • 1,212
  • 1
  • 13
  • 19