I have a button which changes the color of the MainActivity but this works only if the app it is open if I exit the app and open again it return to normal color which is white.
How to store with Shared Preferences do you have any idea how to do that because strings, int and boolean I can save but this function I don' have any idea.
This is my code.
MainActivity.class
public static final String Change_Color = "Change_Color";
private boolean switchOnOff;
setContentView(R.layout.activity_main);
if (switchOnOff == true) {
setColorGreyImageButton();
} else if(switchOnOff == false) {
setColorWhiteImageButton();
}
if(id == R.id.menu_back_white) {
saveColor();
} else if (id == R.id.menu_back_black) {
saveColor2();
}
public void setColorGreyImageButton() {
settings.setColorFilter(Color.parseColor("#757575"));
voiceSearch.setColorFilter(Color.parseColor("#757575"));
share.setColorFilter(Color.parseColor("#757575"));
search.setColorFilter(Color.parseColor("#757575"));
mainView.setBackgroundColor(Color.parseColor("#FFFFFF"));
SharedPreferences in MainActivity
public void saveColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, false);
switchOnOff = sharedPreferences.getBoolean(Change_Color, false);
}
public void saveColor2() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(Change_Color, true);
switchOnOff = sharedPreferences.getBoolean(Change_Color, true);
}
Use these methods in your activity class:
private boolean getChangeColor() {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
return sharedPreferences.getBoolean(getPackageName() + ".change_color", false);
}
private void saveChangeColor(boolean changeColor) {
SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getPackageName() + ".change_color", changeColor);
editor.apply();
}
In onCreate() check the boolean value stored in SharedPreferences:
switchOnOff = getChangeColor();
if (switchOnOff) {
setColorGreyImageButton();
} else {
setColorWhiteImageButton();
}
and when you want to change the value in SharedPreferences call:
saveChangeColor(true);
or
saveChangeColor(false);
Related
Iam not able to store values in shared prefernces.As soon as the activity is closed the no value remains saved. On starting the activity again the ids used to store and fetch data have null values.
Heres is my code.i am not attaching the layout as they will be of no significance.
As I am new to android.There might be some simple thing i a missing.Please help
public class enter_db extends AppCompatActivity
{
String field;
EditText usrtext,idtxt,bananatxt,coconuttxt,timbertxt,bambootxt,goldtxt,garage1txt,garage2txt,garage3txt,garage4txt,garage5txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.db_entry);
usrtext=(EditText)findViewById(R.id.username);
idtxt=(EditText)findViewById(R.id.UserID);
bananatxt=(EditText)findViewById(R.id.banana_count);
coconuttxt=(EditText)findViewById(R.id.coconut_count);
bambootxt=(EditText)findViewById(R.id.banana_count);
timbertxt=(EditText)findViewById(R.id.Timber_count);
goldtxt=(EditText)findViewById(R.id.gold_count);
garage1txt=(EditText)findViewById(R.id.garage_1);
garage2txt=(EditText)findViewById(R.id.garage_2);
garage3txt=(EditText)findViewById(R.id.garage_3);
garage4txt=(EditText)findViewById(R.id.garage_4);
garage5txt=(EditText)findViewById(R.id.garage_5);
SharedPreferences pref=getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
final SharedPreferences.Editor editor = pref.edit();
if(pref.getString("Username",null)!="")
{
field=pref.getString("Username",null);
usrtext.setHint("Username"+field);
}
if(pref.getString("UserID",null)!=null)
{
field=pref.getString("UserID",null);
idtxt.setHint("UserID: "+field);
}
if(pref.getString("Banana",null)!=null)
{
field=pref.getString("Banana",null);
bananatxt.setHint("Banana: "+field);
}
if(pref.getString("Coconut",null)!=null)
{
field=pref.getString("Coconut",null);
coconuttxt.setHint("Cococnut: "+field);
}
if(pref.getString("Timber",null)!=null)
{
field=pref.getString("Timber",null);
timbertxt.setHint("Timber: "+field);
}
if(pref.getString("Bamboo",null)!=null)
{
field=pref.getString("Bamboo",null);
bambootxt.setHint("Bamboo"+field);
}
if(pref.getString("Gold",null)!=null)
{
field=pref.getString("Gold",null);
goldtxt.setHint("Gold: "+field);
}
if(pref.getString("Garage1",null)!=null)
{
field=pref.getString("Garage1",null);
garage1txt.setHint("Garage1 :"+field);
}
if(pref.getString("Garage2",null)!=null)
{
field=pref.getString("Garage2",null);
garage2txt.setHint("Garage2 :"+field);
}
if(pref.getString("Garage3",null)!=null)
{
field=pref.getString("Garage3",null);
garage3txt.setHint("Garage3 :"+field);
}
if(pref.getString("Garage4",null)!=null)
{
field=pref.getString("Garage4",null);
garage4txt.setHint("Garage4 :"+field);
}
if(pref.getString("Garage5",null)!=null)
{
field=pref.getString("Garage5",null);
garage5txt.setHint("Garage5 :"+field);
}
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
ImageButton ok=(ImageButton)findViewById(R.id.ok);
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
}
}
U missed the apply() / commit() to save chanegs.
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply(); // editor.commit()
apply() is faster and async while commit() is synchronous.
Save value in shared preferences:
SharedPreferences settings =getSharedPreferences("AppName", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
editor. putBoolean(key, value);
editor.commit();
get value from shared preferences:
SharedPreferences settings = getSharedPreferences("AppName", 0);
String value=settings.getString(key, "");
boolean value=settings.getBoolean(key,false);
As in above code you are not saving value of edit text in shared preference on button click,try this way
ok.setOnClickListener(new View.OnClickListener() {
// Start new list activity
public void onClick(View v)
{
editor.putString("Username",usrtext.getText().toString());
editor.putString("UserID",idtxt.getText().toString());
editor.putString("Banana",bananatxt.getText().toString());
editor.putString("Coconut",coconuttxt.getText().toString());
editor.putString("Timber",timbertxt.getText().toString());
editor.putString("Bamboo",bambootxt.getText().toString());
editor.putString("Gold",goldtxt.getText().toString());
editor.putString("Garage1",garage1txt.getText().toString());
editor.putString("Garage2",garage2txt.getText().toString());
editor.putString("Garage3",garage3txt.getText().toString());
editor.putString("Garage4",garage4txt.getText().toString());
editor.putString("Garage5",garage5txt.getText().toString());
editor.apply();
Intent i=new Intent(getApplicationContext(),Garage.class);
startActivity(i);
}
});
editor.putString("Garage5",garage5txt.getText().toString());
editor.commit();
I'm trying to save an int I get from an EditText, and as people said it will be best with SharedPreference, I listened, but everytime i'm trying to save/load, the program crashes! any ideas?
public static final String MY_PREFS_NAME = "MyPrefsFile";
String getsturdvalue;
int sturd;
EditText sturdadapter;
int sturdadaptercount;
public void onSave(View view) {
SharedPreferences.Editor editor = (SharedPreferences.Editor) getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
editor.putInt(getstrengthvalue, strnth);
editor.apply();
}
public void onLoad(View view) {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText= prefs.getString("text", null);
if (restoredText != null) {
int insertvalue = prefs.getInt("insertvalue", strnth);
int adapter = prefs.getInt("adapter", strengthadaptercount);
}
strengthadapter.setText(prefs.getInt("" ,strengthadaptercount));
}
It seems a ClassCastException. Try this:
public void onSave(View view) {
SharedPreferences.Editor editor = (SharedPreferences.Editor)
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
// ...
}
i want to store button favourite state in the viewpager which i m developing so that users can always look back the images that they have book-marked as favourite. The button state is stored, however, once i reopen the application, the button state has not changed. Is it because the activity has destroyed? How to store the state of button in the viewpager?
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
showProgress();
imageView = (ImageView) findViewById(R.id.btn_favourite);
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
imageView.setOnClickListener(new View.OnClickListener() {
Boolean stateBtn= sharedPreference.getBtnState(context);
#Override
public void onClick(View v) {
// Boolean stateBtn= sharedPreference.getBtnState(context);
if(!stateBtn) {
sharedPreference.save(context, mUrl);
sharedPreference.saveBtnState(context, stateBtn);
Toast.makeText(context,
"Added to Favourite!",
Toast.LENGTH_SHORT).show();
imageView.setColorFilter(Color.argb(255, 249, 0, 0));
}
else
{
sharedPreference.saveBtnState(context, stateBtn);
imageView.setColorFilter(Color.argb(255, 192, 192, 192));
}
}
});
View photoRow = inflater.inflate(R.layout.item_image, container,
false);
ImageView image = (ImageView) photoRow.findViewById(R.id.img_flickr);
// added imageloader for better performance
StaggeredDemoApplication.getImageLoader().get(imageArrayList[position],
ImageLoader.getImageListener(image, R.drawable.bg_no_image, android.R.drawable.ic_dialog_alert), container.getWidth(), 0);
((ViewPager) container).addView(photoRow);
stopProgress();
return photoRow;
}
Here is the code of shared preference
public class SharedPreference {
public static final String PREFS_NAME = "AOP_PREFS";
public static final String PREFS_STATE="AOP_BTN";
public static final String PREFS_KEY = "AOP_PREFS_String";
public static final String PREF_BTN_KEY = "AOP_PREF_BTN";
public SharedPreference() {
super();
}
public void save(Context context, String text) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putString(PREFS_KEY, text); //3
editor.commit(); //4
}
public String getValue(Context context) {
SharedPreferences settings;
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
text = settings.getString(PREFS_KEY, null);
return text;
}
public void clearSharedPreference(Context context) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.clear();
editor.commit();
}
public void removeValue(Context context) {
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
editor = settings.edit();
editor.remove(PREFS_KEY);
editor.commit();
}
public void saveBtnState(Context context, Boolean stateBtn) {
SharedPreferences settings;
Editor editor;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
settings = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE); //1
editor = settings.edit(); //2
editor.putBoolean(PREF_BTN_KEY, stateBtn);//added state for button
editor.commit(); //4
}
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
}
no because you are calling wrong preference . you have to use PREFS_STATE instead of PREFS_NAME and also use PREF_BTN_KEY instead of PREFS_NAME . This is because while saving button state you are using preference with key PREFS_STATE and put boolean value with PREF_BTN_KEY .
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_STATE, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
Change The getBtnState method
public boolean getBtnState(Context context)
{
SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
boolean switchState = prefs.getBoolean(PREF_BTN_KEY, false);
return switchState;
}
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.
I have a listview populated from the database, and a checkbox for each row. Using putExtras to pass values to a TextView to another Activity. Now when you restart the app I want to display in TextView the last value selected with checkboxes. I need SharedPreferences or is there a method? Thanks
Save your checkbox in preference as below:
//method to load the sharedpreferences.
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
String name = sharedPreferences.getString("storedName", "YourName");
if (checkBoxValue) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
textview.setText(name);
}
//store boolean value of checkbox in sharedpreferences.
private void savePreferences(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
//store the string sharedpreference.
private void savePreferences(String key, String value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
savePreferences("CheckBox_Value", checkBox.isChecked());
savePreferences("storedName", textview.getText().toString());
}