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();
// ...
}
Related
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);
How can I store already existing string value in SharedPreferences on button click? I have a TextView and a button: the TextView contains certain string and I want to store that in SharedPreferences on button click.
To write it:
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("Yourkey", textView.getText()+"");
editor.commit();
}
});
And to read it:
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String string = sharedPref.getString("Yourkey","default");
Here are methods which I use everytime to store data in shared-preferences:
private SharedPreferences app_prefs;
private final String DEVICE_TOKEN = "device_token";
public PreferenceHelper(Context context) {
app_prefs = context.getSharedPreferences(AndyConstants.PREF_NAME,
Context.MODE_PRIVATE);
this.context = context;
}
public void putDeviceToken(String deviceToken) {
Editor edit = app_prefs.edit();
edit.putString(DEVICE_TOKEN, deviceToken);
edit.commit();
}
public String getDeviceToken() {
return app_prefs.getString(DEVICE_TOKEN, null);
}
In the first method I create the shared-preferances object, in the second method I use it to put data and in third method to get data any where you need.
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 using SharedPreferences to keep the information about user's weight, which I need in my application. The problem is, how to set a default value (eg. 75 kg) automatically after installation? I know how to do it via .xml, but how to do this programmatically?
My code:
public class SettingsDialogFragment extends DialogFragment{
public static final String PREFS_NAME = "settings";
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Data.weight = weight;
SharedPreferences prefs = getActivity().getSharedPreferences(PREFS_NAME, 0);
Editor editor = prefs.edit();
editor.putInt("key_weight", weight);
editor.commit();
Data.ifMale = ifMale;
checkedRadio = rg.getCheckedRadioButtonId();
System.out.println("numer radio" +checkedRadio);
}
});
return builder.create();
}
}
Try this way, please.
SharedPreferences prefs = getActivity().getSharedPreferences(
PREFS_NAME, 0);
if (prefs.getInt("key_weight", null) == null) {
Editor editor = prefs.edit();
editor.putInt("key_weight", 75);
editor.commit();
}
For first time use this, or else use your code only(means without if condition).
getInt takes a default value.
prefs.getInt("key_weight", 75)
Or in a more mainstream style....
public class AppPreferences {
private SharedPreferences mPreferences;
Public AppPreferences(SharedPreferences preferences)
{
this.mPreferences = preferences;
}
private static final String KEY_WEIGHT_KEY = "key_weight";
private static final int DEFAULT_KEY_WEIGHT = 75;
public static int getKeyWeight()
{
return mPreferences.getInt(KEY_WEIGHT_KEY,DEFAULT_KEY_WEIGHT);
}
}
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());
}