How can i access shared preferences from another view - android

I have following code in settings.java:
public static int numberOfQuestions = 0;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
final RadioGroup rg_numberOfQuestions = (RadioGroup) findViewById(R.id.radioGroupQuestions);
rg_numberOfQuestions.setOnCheckedChangeListener(this);
RadioButton rbtn = ((RadioButton) rg_numberOfQuestions.findViewById(pref.getInt("NQ", 0)));
if(rbtn!=null)
rbtn.setChecked(true);
}
public void onCheckedChanged(RadioGroup rg, int i) {
switch (rg.getCheckedRadioButtonId())
{
case R.id.rb_0to10:
numbersBetween = 10;
break;
case R.id.rb_0to25:
numbersBetween = 25;
break;
case R.id.rb_0to50:
numbersBetween = 50;
break;
}
if(rg.getCheckedRadioButtonId() == R.id.rb_0to10 || rg.getCheckedRadioButtonId() == R.id.rb_0to25 || rg.getCheckedRadioButtonId() == R.id.rb_0to50)
{
savePref("NB", rg.getCheckedRadioButtonId());
}
}
This is code to save and access preference:
private void savePref(String key, int value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putInt(key, value);
editor.commit();
}
private void savePref(String key, Boolean value) {
pref = getSharedPreferences(Constants.PREF_SETTINGS, 0);
editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
}
}
If i am in settings numberOfQuestions variable gets updated and it works fine in my other view called main.java. But lets say i open main.java directly and not open setting first numberOfQuestions does not have right value. Is there easier way to transfer shared preference value to other view? Or do i need to write all cases in main.java also?

You don't need to do anything special, you can use the same shared preferences from each part of your app in the same way.
You can move the methods to access shared preferences to:
a parent class for all your activities
a static methods in a helper class (you would have to pass context as parameter in this case and be careful not to create a reference to this context to avoid memory leaks).

You can use
numberOfQuestions = getSharedPreferences(Constants.NUM_OF_QUESTIONS, 0);
to initialize its value. then access it anywhere in your application

Related

increase int in textview after button click and keep it threw activities

I'm new to android, and I'm stuck right now.
I'm building an android app.
I have a textview with int value
final int intbut = 40;
hp.setText(String.valueOf(intbut));
I have a button, when clicking on it it add +1, +0 or -1 to the value.
public void onClick(DialogInterface dialog, int which) {
if(answer.getHp() == 1){
hp.setText(String.valueOf(intbut + 1));
Log.i("GameActivity", "json " + answer.getHp());
}
But at the click of the button it also reload the activity so the new value is not saved, how can I save the changed value ?
One option would be using Shared preferences, to save the desired value and retrieve it in any point of your application.
as an example this are create methods to save and retrieve and integer value:
private String PREFS_KEY = "mypreferences";
public void saveValuePref(Context context, int value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
SharedPreferences.Editor editor;
editor = settings.edit();
editor.putInt("myValue", value);
editor.commit();
}
public int getValuePref(Context context) {
SharedPreferences preferences = context.getSharedPreferences(PREFS_KEY, MODE_PRIVATE);
return preferences.getInt("myValue", 0);
}
To save the value use:
saveValuePref(getApplicationContext, intbut);
to retrieve the value use:
int intbut = getValuePref(getApplicationContext);

Boolean Shared Preference is not storing

I am working on an Android game, in which in settings there is an option to turn off/on the sound of game.
I want to store these settings for the game, for this i am using shared preference to store a boolean value.
but issue is Boolean variable is not saving after app is closed.
here is my Code
Button Click Listener which is setting the SharedPreference
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (check == false) {
check = true;
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF, Constants.FIRSTTIME, true);
volume.setBackgroundResource(R.drawable.mute);
Log.e("Check is True", "Preference is True");
} else if (check == true) {
check = false;
volume.setBackgroundResource(R.drawable.volume);
PrefrencesClass.setBoolPreference(mContext,
Constants.APPSPREF,Constants.FIRSTTIME, false);
Log.e("Check is false", "Preference is false");
}
Toast.makeText(getApplicationContext(), "Volume is Clicked",
Toast.LENGTH_SHORT).show();
}
});
My function to set the boolean SharedPreference
public static final void setBoolPreference(Context base, String prefName,
String key, boolean value) {
SharedPreferences userPref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = userPref.edit();
editor.putBoolean(key, value);
editor.commit();
}
This is how i am getting the SharedPreference
public static final boolean getBoolPreference(Context base,
String prefName, String key) {
SharedPreferences usePref = base.getSharedPreferences(prefName,
Context.MODE_PRIVATE);
boolean value = usePref.getBoolean(key, false);
return value;
}
and this is the code where i need to use the sharedpreference saved state to play sound or not
mPlayer = MediaPlayer.create(MainActivity.this, R.raw.stronghold);
if (PrefrencesClass.getBoolPreference(context, Constants.APPSPREF,
Constants.FIRSTTIME) == false) {
mPlayer.start();
mPlayer.setLooping(true);
}
Boolean state is not saving Please Help
Try this
public static void saveBooleanToSharedPref(Context context, String key, boolean value){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(key, value);
editor.commit();
}//saveBooleanToSharedPref
public static boolean getBooleanBySharedPref(Context context, String key){
SharedPreferences settings = context.getSharedPreferences("settings", Context.MODE_PRIVATE);
boolean value = settings.getBoolean(key, true);
return value;
}//getStringBySharedPref
Your set is wrong, because you use putInt method.
You should be able to say:
volume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
check = !check // avoids if statements, same below
SharedPreferences prefsget = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor prefset = prefsget.edit();
prefset.putBoolean(yourBoolVar, !prefsget.getBoolean(yourBoolVar, false));
prefset.commit();
}
});
You can still put an if statement for setting image background. But the what I have above should cut down on a lot of your code. Remember to replace the activity I typed above with your own activity and also for the boolean variable too.

Remember click in Android

I have created an activity that should be displayed only once. In this Activity, I added a button, and click its close and will not reopen anymore when the application is started again. I thought of using SharedPreferences, but I do not get the desired result.
I memorize a data in Shared:
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
Editor edit = userDetails.edit();
edit.clear();
edit.putString( "entrato", "entra" );
edit.commit();
this.finish();
break;
}
}
then, in OnCreate() of the previous activity call the Shared and if the data is present do not open the activity:
//remember click
SharedPreferences userDetails = getSharedPreferences("entrato", MODE_PRIVATE);
String valore = userDetails.getString("entrato", "");
if (valore.equals("entra")){
return;
}else{
Intent intent = null;
intent = new Intent(this, Benvenuto.class);
startActivity(intent);
create share preference class like this:
public class MyPreference {
private static final String APP_SHARED_PREFS = "myPref";
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public MyPreference(Context context) {
this.appSharedPrefs = context.getSharedPreferences(APP_SHARED_PREFS, Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
public boolean loadServices(String servicName) {
return appSharedPrefs.getBoolean(servicName, false);
}
public void saveServices(String servicName, boolean isActivated) {
prefsEditor.putBoolean(servicName, isActivated);
prefsEditor.commit();
}
}
then On Oncreate activity check if service exist so wont show and exit.
public static MyPreference myPref = new MyPreference(this);
if(myPref.loadService("this is not first time")){
thisActivity.finish();
}else {
// so it's first time and you can do what ever you want to do
}
and go on you click events and save service like this.
public static MyPreference myPref = new MyPreference(this);
myPref.saveService("this is not first time");
Try this code instead
// save string
static public boolean setPreference(Context c, String value, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
// retrieve String
static public String getPreference(Context c, String key) {
SharedPreferences settings = c.getSharedPreferences(PREFS_NAME, 0);
settings = c.getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString(key, "");
return value;
}
I have Four activities
Splash
Have 2 Buttons And 1 CheckBox ( Remember Me)
3 & 4. Another Activity
If I check the remember me option using checkbox, then I have to remember the button I have clicked and then start the 3rd or 4th activity directly whenever next start.

How can I save ints to be retained even when the application is not running?

When I click on an option I want a check sign to appear to show it has been purchased. I am using SharedPreferences and have made all the links; however, when I click back or exit and then re-enter the application, the check is gone and any history of anything I did before is gone. How do I save the data so that it is kept even when the application is off or I'm at another page in the game. This is my code so far:
ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades);
update();
coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
+ Replay6.totalCoins;
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
tick1.setAlpha(mYellCheck);
}
public void update() {
TextView coinScore = (TextView) findViewById(R.id.tvScore);
coinScore.setText("You have " + coins + " coins");
tick1 = (ImageView) findViewById(R.id.ivtick1);
ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
ImageView back = (ImageView) findViewById (R.id.ivBack);
back.setOnClickListener(this);
moreYellow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ivMoreYellow:
mYellAlpha = 255;
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
break;
case R.id.ivBack:
Intent i = new Intent ("m.k.zaman.SpotActivity");
startActivity(i);
break;
}
}
EDIT
or Should i just use internal storage?
Try replacing your current onClick call to R.id.ivMoreYellow with this:
case R.id.ivMoreYellow:
mYellAlpha = 255;
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
break;
You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.

How to save the state of rediobutton throughout the application in android?

I have two radio groups and each group has two radiobuttons.
the default value is true (i.e. checked ) for first radiobutton in each group.
When user cliks on any radiobutton and when user comeback from other activities the selections made on these radiogroups/radiobuttons are gone...
how can I save/restore radiogroup/radiobutton selection state ??
here is my java code..for one radiogroup..
final RadioButton radioOn = ( RadioButton )findViewById(
R.id.rbOn );
final RadioButton radioOff = ( RadioButton )findViewById(
R.id.rbOff );
radioOn.setChecked( true );
radioOn.setOnClickListener( auto_lock_on_listener );
radioOff.setOnClickListener( auto_lock_off_listener );
please help.
You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putBoolean("MyBoolean", true);
savedInstanceState.putDouble("myDouble", 1.9);
savedInstanceState.putInt("MyInt", 1);
savedInstanceState.putString("MyString", "Welcome back to Android");
// etc.
super.onSaveInstanceState(savedInstanceState);
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate and also onRestoreInstanceState where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
boolean myBoolean = savedInstanceState.getBoolean("MyBoolean");
double myDouble = savedInstanceState.getDouble("myDouble");
int myInt = savedInstanceState.getInt("MyInt");
String myString = savedInstanceState.getString("MyString");
}
You'd usually use this technique to store instance values for your application (selections, unsaved text, etc.).
Try to save your radio group state by using SharedPreferences
RadioGroup rG1 = (RadioGroup)findViewById(R.id.radioGroup1);
int rG1_CheckId = rG1.getCheckedRadioButtonId();
SharedPreferences rG1Prefs = getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = rG1Prefs.edit();
prefsEditor.putInt("rG1_CheckId", rG1_CheckId);
prefsEditor.commit();
and put this lines for get back the checked radio button id.
SharedPreferences rG1Prefs = this.getSharedPreferences("rG1Prefs", MODE_WORLD_READABLE);
rG1Prefs.getInt("rG1_CheckId", null);
and by using this id checked the radio button.
you can store into the SharedPreference
simple example
SharedPreferences settings = getSharedPreferences("on_off", 0);
boolean silent = settings.getBoolean("onoff", false);
////// to set the value use editor object from the SharedPreferences
Editor editor = settings.edit();
editor.putBoolean("onoff", true);
editor.commit(); // to save the value into the SharedPreference
Use this code -
mFillingGroup.check(whichFilling);
mAddMayoCheckbox.setChecked(addMayo);
mAddTomatoCheckbox.setChecked(addTomato);
/**
* We also want to record the new state when the user makes changes,
* so install simple observers that do this
*/
mFillingGroup.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group,
int checkedId) {
// As with the checkbox listeners, rewrite the
// entire state file
Log.v(TAG, "New radio item selected: " + checkedId);
recordNewUIState();
}
});
CompoundButton.OnCheckedChangeListener checkListener
= new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Whichever one is altered, we rewrite the entire UI state
Log.v(TAG, "Checkbox toggled: " + buttonView);
recordNewUIState();
}
};
mAddMayoCheckbox.setOnCheckedChangeListener(checkListener);
mAddTomatoCheckbox.setOnCheckedChangeListener(checkListener);
}
/**
* Handy helper routine to write the UI data to a file.
*/
void writeDataToFileLocked(RandomAccessFile file,
boolean addMayo, boolean addTomato, int whichFilling)
throws IOException {
file.setLength(0L);
file.writeInt(whichFilling);
file.writeBoolean(addMayo);
file.writeBoolean(addTomato);
Log.v(TAG, "NEW STATE: mayo=" + addMayo
+ " tomato=" + addTomato
+ " filling=" + whichFilling);
}
And, this can help you to do whatever you need.
Use Shared Preferences, To save your radio button's state, Or you can use Application Variables (Variable which is declared globally static in that activity and you can use it in any activity)
But I think Shared Preferences is good..
Look at Android - Shared Preferences
Look at this example How to save login info to Shared Preferences Android(remember details feature)
EDIT:
public class Test extends Activity {
private SharedPreferences prefs;
private String prefName = "MyPref";
private SharedPreferences.Editor editor;
private static final String CHECK_STATE = "checkBox_State";
private boolean check_state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
//---getting the SharedPreferences object....
prefs = getSharedPreferences(prefName, MODE_PRIVATE);
editor = prefs.edit();
radioOn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
check_state = true;
} else {
check_state = false;
}
}
});
// storing in shared preferences...
editor.putBoolean(CHECK_STATE, check_state );
editor.commit();
}
});
}

Categories

Resources