Android button state not stored in viewpager - android

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;
}

Related

Is it possible to save void in SharedPreferences

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);

Storing values in SharedPreferences on button click

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.

Android SharedPreference not working right

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();
// ...
}

Android CheckBox in Listview

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());
}

Storing data in Swipeable UI. Get Context in Fragments

I am using the Scrollable tabs + Swipe Navigation for my project. I used Shared Preferences to store data of a form.
My onClick function for the save button of the page.
public void onClick(View v) {
SharedPreferences.Editor editor3 = settings3.edit();
editor3.putString("address", personal_info_address.getText().toString());
editor3.putString("age", personal_info_age.getText().toString());
editor3.putString("name", personal_info_name.getText().toString());
editor3.putString("diseases", personal_info_diseases.getText().toString());
editor3.commit();
}
I am unable to restore data after I reopen the application.
I am able to save my form details in a normal app with the same code, do I need to do something else as I am using the Scrollable tabs + Swipe Navigation.
EDIT:
I implemented the clickListener in the Fragment Class, here is my code:
public class SettingsFragment extends Fragment {
public static EditText txtMessage;
public static EditText emergencyno;
Button button;
Context context;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.services, container, false);
emergencyno = (EditText) root.findViewById(R.id.settings_number);
txtMessage = (EditText) root.findViewById(R.id.settings_msg);
button = (Button) root.findViewById(R.id.save);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = txtMessage.getText().toString();
String no = emergencyno.getText().toString();
Log.d("HELLO : ", "data1");
SharedPreferences sharedpreferences = context
.getSharedPreferences("MyData", Context.MODE_PRIVATE);
Log.d("HELLO : ", "data2" + context);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("message", msg);
editor.putString("number", no);
editor.commit();
Log.d("HELLO : ", "data3" + msg + no);
String message = sharedpreferences.getString("message",
"defValue");
String phone_no = sharedpreferences.getString("number",
"defValue");
txtMessage.setText(message);
emergencyno.setText(phone_no);
Log.d("HELLO : ", "data4" + message + phone_no);
}
});
return root;
}
}
The log gives the correct values which I require. But on restarting the app the data isnt stored. I need to know how to get the Context.
I was able to solve the problem. The getActivity() in this fragment returned the Main Page of my app where I created the fragments so I defined my sharedpreferences function in the Main Page of the app(i.e. in the activity of this Fragment) as follows:
public static void putPref(String key, String value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static void putPref(String key, Boolean value, Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static String getPref(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getString(key, null);
}
public static boolean getPrefBool(String key, Context context) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
return preferences.getBoolean(key, true);
}
And used the putPref function on clicking the button and getPref function on activity created.

Categories

Resources