Syntax to complete shared preferences for number of clicks count - java

Hi I just need a little bit of a helping hand in completing this shared preferences code I have.
Currently I have a class where I stored in the relevant code for SharedPreferences:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void storeClicks(int count)
{
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, count);
editor.apply();
}
public int getNumberOfClicks(){
int clicksNumber = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
return clicksNumber;
}
}
I want to count the number of clicks for buttons jokes, poems and funnystories from the MainActivity class and the 'select another' button from the Content class. So if each button was clicked 4 times, the total click count should be 16.
I want to keep the number of clicks count even after the app is closed and re-open. It's just the syntax of the counting of the clicks I am unsure of. I think for main activity it is correct but I am unsure on how to store it for the Content class.
TO recap, count the number of clicks for all of those buttons mentioned and this number should be accessible and updated no matter which page the user is in.
Below is the Main Activity class:
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);
SharedPreferencesManager.getInstance(context).storeClicks(clicksCount);
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++;
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
}
Below is Content class:
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
int clicksCount = SharedPreferencesManager.getInstance(context).getNumberOfClicks();
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
finish();
}
});
}
}

Instead of having the two methods getNumberOfClicks() and storeClicks() in your SharedPreferencesManager, you could only have one like this:
public void increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
}
You call this on every click. No need for the activities to know about the clicks count.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(context);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
}
});
...
}
Also there's no need to store your context as a global variable because your activity is already a context itself, you can just use this or MainActivity.this for a context.

Related

How to functionate the second activity through a radio button in the Main_activity?

if I have two activities.
1.Main_Activity
which contain a radio button and an image button.
2.Second_activity extended from Main_activity.
which is intent in Main_activity and contain three radio buttons with the saved state in shared preference.
the vibration, normal and silent mode work on these radio buttons.
the Drvset activity is already intent through the image button.
I want to retrieve the saved state of the radio buttons and Load it through the radio button in the main activity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageButton buttonOne = findViewById(R.id.drvedit);
RadioButton buttondr=findViewById(R.id.drvbtn);
buttonOne.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
System.out.println("Button Clicked");
Intent activity2Intent = new Intent(getApplicationContext(), drvset.class);
startActivity(activity2Intent);
}
});
}
}
public class drvset extends MainActivity {
private RadioButton normal;
private RadioButton silent;
private RadioButton vibrate;
private AudioManager myAudioManager;
final String KEY_SAVED_RADIO_BUTTON_INDEX = "SAVED_RADIO_BUTTON_INDEX";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drvset);
LoadPreferences();
normal = (RadioButton) findViewById(R.id.radioNormal);
silent = (RadioButton) findViewById(R.id.radioSilent);
vibrate=(RadioButton)findViewById(R.id.radiovibrate);
normal.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
normalEnable(v);
}
});
silent.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
silentEnable(v);
}
});
vibrate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
vibrateEnable(v);
}
});
myAudioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
}
public void vibrateEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
status.setText("Current Status: Vibrate Mode");
}
public void normalEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
status.setText("Current Status: Ring Mode");
}
public void silentEnable(View view){
myAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
status.setText("Current Status: Silent Mode");
}
}};
public void SavePreferences(String key, int value){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.apply();
}
public void LoadPreferences(){
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
int savedRadioIndex = sharedPreferences.getInt(KEY_SAVED_RADIO_BUTTON_INDEX, 0);
RadioButton savedCheckedRadioButton = (RadioButton)radioGroup.getChildAt(savedRadioIndex);
savedCheckedRadioButton.setChecked(true);
}
}

savedInstanceState causing a crash while screen rotation

public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE="com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN="com.example.ferhat.geoquiz.answer_shown";
private static final String CHEATER="com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mIsCheater;
public static Intent newIntent(Context packageContext, boolean answerIsTrue){
Intent i=new Intent(packageContext,CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE,answerIsTrue);
return i;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
mIsCheater=true;
setAnswerShownResult();
}
});
if(savedInstanceState!=null){
mIsCheater=savedInstanceState.getBoolean(CHEATER,false);
}
}
private void setAnswerShownResult(){
Intent data=new Intent();
data.putExtra(EXTRA_ANSWER_SHOWN,mIsCheater);
setResult(RESULT_OK,data);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER,mIsCheater);
}
}
I try to solve challenge in Anroid Programming, Big Nerds Ranch Guide (Chap.5)
Challenge asks me to keep Cheat data while rotation of screen and transaction between questions.Main Activity holds questions and CheatActivity has answers from Main activity. And i created BooleanArray to hold cheat data for questions.
Problem is ,i cheated for first question and then when i am in the CheatActivity(CheatPage) of other questions ,program crashes if i rotate the screen.
Error caused by this line savedInstanceState.putBoolean(CHEATER,mIsCheater);
i think i need to clear data from previous Cheat Data(BooleanArray already holding it) but i dont know how to do it.
public class CheatActivity extends AppCompatActivity {
private static final String EXTRA_ANSWER_IS_TRUE = "com.example.ferhat.geoquiz.answer_is_true";
public static final String EXTRA_ANSWER_SHOWN = "com.example.ferhat.geoquiz.answer_shown";
public static final String EXTRA_CHEATED = "com.example.ferhat.geoquiz.cheated";
private static final String CHEATER = "com.example.ferhat.geoquiz.cheated";
private Boolean mAnswerIsTrue;
private TextView mAnswerTextView;
private Button mShowAnswer;
private Boolean mAnswerEverShown;
private Boolean twoStep=false;
//Yeni intent methodu yarattık Cevabı alıyor ve bu activity i başlatıyor
public static Intent newIntent(Context packageContext, boolean answerIsTrue, boolean checked) {
Intent i = new Intent(packageContext, CheatActivity.class);
i.putExtra(EXTRA_ANSWER_IS_TRUE, answerIsTrue);
i.putExtra(EXTRA_CHEATED, checked);
return i;
}
private void setAnswerShownResult(Boolean isAnswerShown) {
Intent data = new Intent();
**if(mAnswerEverShown) {
isAnswerShown=mAnswerEverShown;
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}else {
data.putExtra(EXTRA_ANSWER_SHOWN, isAnswerShown);
setResult(RESULT_OK, data);
}
twoStep=isAnswerShown;**
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cheat);
mAnswerIsTrue = getIntent().getBooleanExtra(EXTRA_ANSWER_IS_TRUE, false);
mAnswerTextView = (TextView) findViewById(R.id.answerTextView);
**mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);**
mShowAnswer = (Button) findViewById(R.id.showAnswerButton);
mShowAnswer.setOnClickListener(new View.OnClickListener() {
//Cevabı gösteriyor ve Kopya çekildi bilgisi veriliyor
#Override
public void onClick(View v) {
if (mAnswerIsTrue) {
mAnswerTextView.setText(R.string.true_button);
} else {
mAnswerTextView.setText(R.string.false_button);
}
twoStep=true;
setAnswerShownResult(twoStep);
}
});
**if (savedInstanceState != null) {
setAnswerShownResult(savedInstanceState.getBoolean(CHEATER, false));
}
}
#Override
public void onSaveInstanceState (Bundle savedInstanceState){
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean(CHEATER, twoStep);
}
}**
i found solution like for every situation.
first think i did; i get info from main activity
mAnswerEverShown = getIntent().getBooleanExtra(EXTRA_CHEATED, false);
And Then i changed setAnswerShownResult for two situation.If it is not cheated ever program sends current data(cheated or not).
i marked where i changed with *.
You need to putBoolean before callback the super method.
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putBoolean(CHEATER,mIsCheater);
super.onSaveInstanceState(savedInstanceState);
}
if not the CHEATER won't be saved and you can't call it when resume activity

RTF editor cannot resolve symbol "editor"

I am beginner in programming on Android. I would like to check, how this library works. I want to check one of the possibilities in my own project, but there is a problem - I do not know how to declare variable "editor" and also "preview"
MainActivity code:
public class MainActivity extends AppCompatActivity {
private RichEditor mEditor;
private TextView mPreview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEditor = (RichEditor) findViewById(R.id.editor);
mEditor.setEditorHeight(100);
mEditor.setEditorFontSize(12);
mEditor.setPadding(10, 10, 10, 10);
mEditor.setPlaceholder("Insert text here...");
mPreview = (TextView) findViewById(R.id.preview);
mEditor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
#Override public void onTextChange(String text) {
mPreview.setText(text);
}
});
RichEditor editor = (RichEditor) findViewById(R.id.editor);
editor.setOnTextChangeListener(new RichEditor.OnTextChangeListener() {
#Override
public void onTextChange(String text) {
// Do Something
Log.d("RichEditor", "Preview " + text);
}
});
findViewById(R.id.action_bold).setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
mEditor.setBold();
}
});
}

How to make the button loads the previous page in Android?

I have search a lot in different sites to solve this problem but I can't till now.
I have a simple app with 50 articles, two buttons, previous and next.
All works fine till the last article 50 where the problem is that the user can't choose the previous button 49, only can load from the beginning.
Here is my code: MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView meditCenterText;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
meditCenterText = (TextView) findViewById(R.id.editCenterText);
mStartButton = (Button) findViewById(R.id.startButton);
meditCenterText.setMovementMethod(new ScrollingMovementMethod());
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String TextView = meditCenterText.getText().toString();
startStory(TextView);
}
});
}
private void startStory(String TextView) {
Intent intent = new Intent(this, StoryActivity.class);
intent.putExtra("TextView", TextView);
startActivity(intent);
}
#Override
protected void onResume() {
super.onResume();
meditCenterText.setText("..... ");
}}
StoryActivity.java
public class StoryActivity extends AppCompatActivity {
public static final String TAG = StoryActivity.class.getSimpleName();
private Story mStory = new Story();
private ImageView mImageView;
private TextView mTextView;
private Page mCurrentPage;
private String mName;
private Button mPreviousButton;
private Button mNextButton;
private ScrollView mScrollView;
private Button mStartButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_story2);
//Intent intent = getIntent();
//mName = intent.getStringExtra(getString(R.string.key_name));
if(mName == null){
mName = "";
}
Log.d(TAG, mName);
mImageView = (ImageView)findViewById(R.id.storyImageView);
mTextView = (TextView)findViewById(R.id.storyTextView);
mPreviousButton = (Button)findViewById(R.id.previousButton);
mNextButton = (Button)findViewById(R.id.nextButton);
mTextView.setMovementMethod(new ScrollingMovementMethod());
loadPage(0);
}
private void loadPage(int choice){
mCurrentPage = mStory.getPage(choice);
Drawable drawable = getResources().getDrawable(mCurrentPage.getImageId());
mImageView.setImageDrawable(drawable);
String pageText = mCurrentPage.getText();
//add the name if placeholder included.
//pageText = String.format(pageText,mName);
mTextView.setText(pageText);
if(mCurrentPage.isSingle()){
mPreviousButton.setVisibility(View.VISIBLE);
mNextButton.setText("Start From The Beginning");
mNextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPreviousButton.setVisibility(View.VISIBLE);
loadPage(0);
}
});
}else{
mPreviousButton.setText(mCurrentPage.getChoices().getText1());
mNextButton.setText(mCurrentPage.getChoices().getText2());
mPreviousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int previousPage = mCurrentPage.getChoices().getPreviousPage();
loadPage(previousPage);
}
});
mNextButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int nextPage = mCurrentPage.getChoices().getNextPage();
loadPage(nextPage);
}
});
}}
}
Thanks for help.
It's probably the logic in your Page class. Have a proper look at it, otherwise from the android side everything is alright. One last thing, you should probably use a ViewPager for your app instead of changing the text every time you load a new oage

Use a string (from input) in another class

I have a class in which a string is taken from an input. I want to use the value of the input in a second class.
public class Incontrare extends ActionBarActivity {
public static String nome1=null;
public String variabileNome;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare);
Button button1 = (Button) findViewById(R.id.button1Nome);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
alertDia(); //takes the input from variabileNome
nome1 = variabileNome;
TextView textv1 = (TextView) findViewById(R.id.textView1);
textv1.setText(nome1);
}
});
public static String getNome1() {return nome1;}
}
}
And the second class:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_incontrare_persona1);
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
I tried the second class also in this way:
public class IncontrarePersona1 extends ActionBarActivity {
String nome1=Incontrare.getNome1();
public static String no1;
b1=(Button)findViewById(R.id.play);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Incontrare no1= new Incontrare();
String n1= no1.nome1;
String toPrint = "There is " + nome1;
Toast.makeText(getApplicationContext(), toPrint, Toast.LENGTH_SHORT).show();
}
});
}
Where is the mistake? Why do I get always null?
Any help is appreciated. Thanks :)
If you are jumping from activity to another use Bundle.
Bundle example -
Set value
Intent i = new Intent();
i.setClass(this, IncontrarePersona1.class);
i.putExtra("text", "some text");
startActivity(i);
Get Value:
Bundle extras = getIntent().getExtras();
if (extras != null)
{
String data= extras.getString("text");
//data is your param
}
Otherwise use static class with static variables as Will McG said.
I think the issue is that when the second Activity is brought into focus, the data in the previous Activity is lost.
Create a separate class to hold your static variables that both Activitys can access.
Edit:
Another method I use for passing data is the SharedPreferences if I'm worried about the entire application losing focus.

Categories