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();
}
});
}