appPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Also tried by creating a new prefs file by name, on both the activity and fragment, still nothing.
boolean firstRun = appPrefs.getBoolean("firstrun", true);
if (firstRun) {
rotate_hint.setVisibility(View.VISIBLE);
} else {
rotate_hint.setVisibility(View.GONE);
}
always, always, returns true.
public void hide_list_hint() {
if (rotate_hint.getVisibility() == View.VISIBLE) {
rotate_hint.setVisibility(View.GONE);
Editor prefsEditor;
prefsEditor = appPrefs.edit();
prefsEditor.putBoolean("firstrun", true); <- facepalm
prefsEditor.commit();
}
}
I dont know of a way to perhaps try this in the fragments onCreate or onActivityCreated because i need access to the 'rotate_hint' view, which comes from the inflated view in the onCreateView.
You put true, if null you get true. Of course it will return true. Change this line;
prefsEditor.putBoolean("firstrun", false);
i should note to your code where :1-
appPrefs.getBoolean("firstrun", true);
if you not save "fristrun" key the defult value will be true i Guess it should be false2-
if (rotate_hint.getVisibility() == View.VISIBLE) {}
you should save your state of Visibility true in this if and on else save false for this state (for better Readability)
i use this saving and restoring method on my fragment as :
for restoring One CheckBox :
public void onViewCreated(View view, Bundle savedInstanceState) {
SharedPreferences Setting = getSherlockActivity()
.getSharedPreferences(PREFERENCENAME, 0);
boolean Check=Setting.getBoolean(
"NotifyChange", false);
CheckBox Changebox = (CheckBox) view.findViewById(
R.id.checkbox);
Changebox.setChecked(Check);
}
and for saving state of CheckBox :
public void onDestroyView() {
// TODO Auto-generated method stub
super.onDestroyView();
CheckBox Changebox = (CheckBox) getView().findViewById(
R.id.checkbox);
SharedPreferences Setting = getSherlockActivity()
.getSharedPreferences(PREFERENCENAME, 0);
Editor editor = Setting.edit();
editor.putBoolean("NotifyChange",Changebox.isChecked);
editor.commit();
hope to be useful :)
Related
I have a textview that when user clicks it, I want it to be invisible. But I want it to stay invisible, even after user has reloaded the app, using "sharedpreferences". How to get shared preferences working and then recalled correctly?
This is my code for storing the preference when user clicks the textview:
textView.setVisibility(View.INVISIBLE);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("was_clicked", true);
editor.commit(); // commit changes
So I understand this will store a true/false boolean in shared preferences called" was_clicked".
But now how do I have it checked for "true" in the onCreate method of the activity and then have it set TextView to view.INVISIBLE if was_clicked = true?
Check out this article. But to answer your question specifically
if (getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE).getBoolean("was_clicked", false))
textView.setVisibility(View.INVISIBLE);
You can check the value using this method:
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
boolean wasClicked = pref.getBoolean("was_clicked",false);
if (wasClicked){
textView.setVisibility(View.INVISIBLE);
}else {
textView.setVisibility(View.VISIBLE);
}
In your onCreate method you should create preferences and read from them like this:
static final String PREFERENCES_NAME = "MyPref";
static final String WAS_CLICKED_NAME = "was_clicked";
#Override
void onCreate()
{
SharedPreferences preferences = getApplicationContext().getSharedPreferences(PREFERENCES_NAME, MODE_PRIVATE);
boolean invisible = preferences.getBoolean(WAS_CLICKED_NAME, false); // 2nd argument is the default value
if (invisible)
{
textView.setVisibility(View.INVISIBLE);
}
}
getBoolean method will read value of "was_clicked" preference. 2nd argument will be returned if you haven't yet put value "was_clicked" to shared preferences, so you can return false if you haven't put this preference to show the textView.
Please help me! Checkbox does not save state after restarting the app
I have a ListView with CheckBoxes and I want that when user selects any check box and closes the application, and again opens the application, the same CheckBoxes should be selected. i.e I have to save the state of the CheckBoxes
// custom BaseAdapter class
...
boolean [] itemChecked;
//getView ...
//getSharedPreferences
sharedPrefs = context.getSharedPreferences(PACKAGE_NAME, Context.MODE_PRIVATE);
//Click ckeckbox
viewHolder.check_task.setChecked(sharedPrefs.getBoolean(PACKAGE_NAME , false));
viewHolder.check_task.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//SharedPreferences
SharedPreferences.Editor editor = context.getSharedPreferences(PACKAGE_NAME , Context.MODE_PRIVATE).edit();
if (viewHolder.check_task.isChecked()) {
//if value is false
itemChecked[i] = true;
viewHolder.check_task.setChecked(true);
//put True
editor.putBoolean(PACKAGE_NAME, true);
editor.apply();
} else {
//if value is false
itemChecked[i] = false;
viewHolder.check_task.setChecked(false);
//put False
editor.putBoolean(PACKAGE_NAME, false);
editor.apply();
}}}); return myView; }
You are always setting the last checked box state in shared preferences since you are using the same key each time. If you want to set multiples you would have to define a new key for each boolean using something like editor.putBoolean(PACKAGE_NAME + index, true); then retrieve it using the same logic. This will result in each index having an entry in shared preferences. Another approach would be to use GSON to save the entire array in onPause and restore it when the app is relaunched.
How can I have a separate preference for each checkbox saving whether it was clicked or not? I have code that works for one and I can repeat it to make it work for each one but I feel I should be able to change it so I don't have so much repeat code.
In onCreate
CheckBox checkbox = (CheckBox) findViewById(R.id.description);
CheckBox checkbox1 = (CheckBox) findViewById(R.id.description1);
SharedPreferences sharedPref = getSharedPreferences("mypref", MODE_PRIVATE);
SharedPreferences sharedPref1 = getSharedPreferences("mypref1", MODE_PRIVATE);
boolean checked = sharedPref.getBoolean("checked", false);
boolean checked1 = sharedPref1.getBoolean("checked1", false);
checkbox.setChecked(checked);
checkbox1.setChecked(checked1);
My click handler
public void handleCheckBoxClick(View view) {
CheckBox tmpChkBox = (CheckBox) findViewById(view.getId());
if(tmpChkBox.isChecked())
{
tmpChkBox.setBackgroundColor(Color.BLUE);
SharedPreferences sharedPref = getSharedPreferences("mypref", MODE_PRIVATE);
sharedPref.edit().putBoolean("checked", true).commit();
}
else
{
tmpChkBox.setBackgroundColor(Color.RED);
SharedPreferences sharedPref = getSharedPreferences("mypref", MODE_PRIVATE);
sharedPref.edit().putBoolean("checked", false).commit();
}
}
I got it to work by making another click handler and referring to that which you see in the onCreate where I make a whole separate preference. Is there a way to make one preference that can be used on each check box?
I am trying to save the state of a checkbox while using SharedPreferences. I have spend hours on this problem...which I sure is easy to solve. I have been following the tutorial here
However, I do not understand what setSilent is and what I have to change it to within my own code. setSilent has been changed to checked in the below code based on one of the answers. I have searched through stackoverflow a lot and found loads of related answers but nothing has worked and the setSilent (sometimes a different name) error is always persistent. I have posted my code below.
SuikodenFragment.java -- The error is here.
Boolean checked;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.suikoden_main_activity1, container, false);
// you can use findViewById() using the above 'view'
// get the listview
expListView = (ExpandableListView) view.findViewById(R.id.suikodenList1);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
checked = true;
return view;
}
public void onStart() {
super.onStart(); // Always call the superclass method first
SharedPreferences settings = getActivity().getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
boolean isChecked = settings.getBoolean("Tick the Box", checked);
checked(isChecked);
//if(isChecked)
//checkBox.setChecked(true);
}
The code below is placing the checkbox state which might help understand my problem.
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkboxTick);
checkBox.setOnCheckedChangeListener(this);
if (isChecked)
// Add the tick to the box
//Log.d(TAG, "Tick the box");
checked = true;
else
// Remove the tick in the box
//Log.d(TAG, "Untick the box");
checked = false;
}
#Override
public void onStop(){
super.onStop();
SharedPreferences settings = getActivity().getSharedPreferences(suikodenprefs, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Tick the Box",checked).commit();
}
I really hope someone can help with this. It may seem like a stupid problem but if it can be solved then I can complete a huge section of my app. The following link is the closest to my own code...but when i implement their solution, checkBoxView flags up as an error Android saving state of checkbox if exit app. I am a beginner so I apologise...thanks in advance!
You need to create a class variable which gets changed in your onCheckedChangedListener and then save it in shared preferences in your onStop() method.
At the top of your activity declare a Boolean variable, lets call it checked.
Boolean checked;
It's good practice to initialize a variable so do that in you onCreate method.
checked = true;
In your onCheckedChanged method set the value of 'checked' to true or false depending on the state.
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
CheckBox checkBox = (CheckBox) expListView.findViewById(R.id.checkbox_tick);
checkBox.setOnCheckedChangeListener(this);
if (isChecked)
checked = true;
else
checked = false;
}
In your onStop method save the value of your checked variable.
#Override
public void onStop(){
super.onStop();
SharedPreferences settings=getActivity().getSharedPreferences(suikodenprefs,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("Tick the box",checked).commit();
}
i am creating number of check boxes dynamically and i have done some logic to select only one at a time . now i just want to save the state of the selected checkbox and when i come back from the next screen it should be selected. below i have given the code for checkbox
cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
if (hash.size() > 0) {
hash.get("1").setChecked(false);
}
hash.put("1", buttonView);
selAnyone = true;
} else {
hash.clear();
selAnyone = false;
}
Edit:
Whenever you are navigating to the current activity to the next activity , save the id of selected check box like this
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkboxid","1");
editor.commit();
or simply send it via Intent
yourintent.putExtra("checkboxid","1"); // selected checkbox id
And then
If you are using the intent instead of sharedpreferences put the same extra when navigating back to the current screen.
First using SharedPreferences:
In the onCreate of your Activity check whether pref contains checkbox id or not
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name",null); // if the preference doesn't exist it returns null
if(name!=null)
{
int checkedid=Integer.parseInt(name);
checkbox[checkid].setChecked(true);
}
Same logic follows for the intent extra also check for checkboxid , if it doesn't exist don't check anything, if it exists check the checkbox with assoicated id
Use SharedPreferences
Example:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("checkboxid","1");
editor.commit();
Get like this
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","checkboxid");