Android Using SharedPreferences to save and retrieve values - Counter - android

Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event - the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.
Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.
The code i am using is as follows:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
Results.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
Any help to guide me would be much appreciated.Thank you

You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:
getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();

Simply make a Preferences class
public class Preferences {
String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;
Preferences(Context context) {
mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}
public void setAddCount(int count) {
SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
prefEditor.putInt("count", count);
prefEditor.commit();
}
public int getAddCount() {
return mysticMatrixPref.getInt("count", 0);
}
}
and in your MainActivity.java put this code
public class MainActivity extends Activity implements OnClickListener {
ImageButton add;
Preferences cpObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Preferences(getApplicationContext());
/*
* getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
*/
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cpObj = new Preferences(getApplicationContext());
cpObj.setAddCount(cpObj.getAddCount() + 1);
}
});
}
}
And in your result activity just get the count's value
import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;
public void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
DisplayResults.setText(cpObj.getAddCount());
}
} }
By this you will get the default value of result as '0' and you can set that in your Preferences class

Use a method like this:
public static void SavePreference(Context context, String key, Integer value) {
SharedPreferences.Editor editor = PreferenceManager
.getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
.edit();
editor.putInt(key, value);
editor.commit();
}
and in you onclick after counter++ add this:
SavePereference(context, "GAME_PREFERENCES_SCORE", counter);

Related

How do I create a button dynamically based on user input?

I am trying to make an app where the user types in text and presses enter and a button is dynamically placed on a different activity with its text set as what the user inputs. I am not sure how to do this, I was thinking of saving the user input in a sharedPreference but I am not sure where to go from there.
package com.example.opisa;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor= sharedPref.edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
}
public void addGoalText(View view) {
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
} else {
mText.setText(name.getText().toString());
}
}
//put your value
editor.putString("goals", name);
//commits your edits
editor.commit();
}
After the user types in what he wants,I would like the mText to be the value of text on a button that dynamically appears on a different activity.
In Your First Activity Write
public class AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences setValue ;
//now get Editor
SharedPreferences.Editor valueEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
}
public void addGoalText() {
valueEditor = setValue.edit();
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
valueEditor.putString("key","Didn't type");
} else {
mText.setText(name.getText().toString());
valueEditor.putString("key", String.valueOf(name.getText()));
}
valueEditor.apply();
}
}
If you are calling addGoalText somewhere , if not use onchangelistener
In Your Second Activity in which you have button
public class SecondActivity extends AppCompatActivity {
SharedPreferences setValue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);// your layout
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
Button your_button =findViewById(R.id.buttonId);//write your own ID
String S = setValue.getString("key","defaultValue");
your_button.setText(S);
}
}

Sharedprefrences not saving?

When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));

Method stops running after switching activities

In this app the users score is supposed to increase every second or so, and they can use that score and buy upgrades from the second Activity. When the user starts the app the program works fine, but when they go from the first activity to the second and back it stops updating the textview with the score that increases every second. Can you guys explain whats going on?
package com.example.navjeevenmann.mytycoon;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private Button myButton;
private int Counter;
private Button myButton2;
private TextView myTextView;
Handler handler = new Handler();
private int add = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
if (bundle.containsKey("Count")) {
Counter = bundle.getInt("Count");
}
if (bundle.containsKey("Add")) {
add = bundle.getInt("Add");
}
}
myButton = (Button) findViewById(R.id.button);
myButton2 = (Button) findViewById(R.id.button2);
myTextView = (TextView) findViewById(R.id.textView);
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Counter = ButtonCounter(Counter);
}
});
myButton2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(),
SecondActivity.class);
intent.putExtra("Count", Counter);
startActivity(intent);
}
});
handler.postDelayed(new Runnable() {
#Override
public void run() {
Counter= AutoCounter(Counter, add);
Display(Counter);
handler.postDelayed(this, 1000);
}
},100);
}
public int ButtonCounter(int Counter) {
Counter += 1;
return Counter;
}
public int AutoCounter(int Counter, int add) {
Counter += add;
return Counter;
}
public void Display(int Counter) {
String man = String.valueOf(Counter);
myTextView.setText("$" + man);
}
}
You start the counting handler only inside onCreate() method.
When you go back from SecondActivity to MainActivity the onResume() method is called, So
You need to start the counting inside onResume() method.
P.S Make sure to check for nulls before updating you UI from postDelay().
Your Activity might be destroyed by the time the code runs, make sure your TextView is not null before updating.

Checkbox Startup Data

I am trying to create an Activity that when the application starts up it will check if the checkbox is checked. If it is checked I want it to open up a second Activity where it opens up the NavDrawer instead of the current activity. Any input would be helpful. Thank you in advance.
package com.example.platinumirish.runassistwithdrawer;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import com.example.platinumirish.runassistwithdrawer.IntroPage2Activity;
import com.example.platinumirish.runassistwithdrawer.NavDrawer;
import com.example.platinumirish.runassistwithdrawer.R;
public class MainActivity extends AppCompatActivity {
private static final String Startup_Identify = "checkbox_setting";
private CheckBox mCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckBox = (CheckBox) findViewById(R.id.checkBox);
// Set the initial state of the check box based on saved value
mCheckBox.setChecked(isCheckedSettingEnabled());
Button btnOne =(Button)findViewById(R.id.NextP1_P2);
btnOne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),IntroPage2Activity.class);
startActivity(intent);
}
});
Button btnTwo =(Button)findViewById(R.id.NextP1_Main);
btnTwo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),NavDrawer.class);
startActivity(intent);
}
});
}
#Override
public void onPause() {
super.onPause();
// Persist the setting. Could also do this with an OnCheckedChangeListener.
setCheckedSettingEnabled(mCheckBox.isChecked());
}
/**
* Returns true if the setting has been saved as enabled,
* false by default
*/
private boolean isCheckedSettingEnabled() {
return PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(Startup_Identify, false);
}
/**
* Persists the new state of the setting
*
* #param enabled the new state for the setting
*/
private void setCheckedSettingEnabled(boolean enabled) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean(Startup_Identify, enabled)
.apply();
}
}
You can achieve this by checking if the checkbox is checked and starting an other activity.
private CheckBox mCheckBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCheckBox = (CheckBox) findViewById(R.id.checkBox);
// Set the initial state of the check box based on saved value
mCheckBox.setChecked(isCheckedSettingEnabled());
if (mCheckBox.isChecked()) {
Intent myIntent = new Intent(this, AvitivityName.class);
startActivity(myIntent);
}
//Rest of ur code

Continue from the last counter when reopen the android application

I am new in Android programing. I want to make an application. The button text increase whenever the user click on it. My counter is reseted when the application is closed. How can I store the last counter value and call it again when the application is reopened?
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
}
EDIT:
I try to use this Shared Preferences but I got eror about "setSilent" and "mSilentMode". Help please
My new code
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
private int c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
final Button button = (Button) findViewById(R.id.buttonClick);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
c++;
button.setText(Integer.toString(c));
}
});
}
#Override
protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
It depends, are you asking how to preserve a variable across an app's lifespan or between different lifespans?
If it's across different lifespans, you can write it to disk and then read it onCreate.
If you need to do it across one lifespan, it depends on your use case, but generally putting it in a global, static variable would do the trick!
If this is unclear and you'd like some sample code, please, don't be afraid to ask! : )
You can save your c value in the Preference when your activity is going to be closed, and when you rise up your activity you set your c variabile to the previous value
Use this snippet out of your onClickListener: To get the int if there is any
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
int ca = hhii.getInt("c_value2", 0);
button.setText(ca+"");
Use this in your onClickListener: To save the int as the user clicks the button-much better than saving it in onBackPressed or OnDestroy or whatever
c++;
button.setText(Integer.toString(c));
SharedPreferences hhii = getSharedPreferences("c_value", MODE_PRIVATE);
hhii.edit().putInt("c_value2",c).commit();
Regards from Iran,
Gabriel

Categories

Resources