I have 5 checkboxs and when they are clicked they set a boolean in an abstract class to true or false using a onCheckedChangeListener. Example:
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked)
{
if(isChecked)
{
CheckboxData.checked = true;
}
else if(!isChecked)
{
CheckboxData.checked = false;
}
}
});
However when I leave the app and return the checkboxes are not clicked anymore, yet the boolean values are still true. How can I make the app remember that the check boxes are clicked.? Should I just check the boolean values in the main activity onCreate and set the checkboxs to checked or not then or is there a better/faster way to make the app remember the checkboxs states?
Just added this in the main activities onCreate method:
if(CheckboxData.checked)
{
CheckBox checkbox = (CheckBox) findViewById(R.id.checkbox);
checkbox.setChecked(true);
}
But it does nothing
when Activity get destroyed check the checkbox state if true , and add the checkbox state in shared Preference
#Override
public void onDestroy() {
if(CheckboxData.checked){
SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
prefs.edit()
.putBoolean("CheckboxData",true)
.commit();
}
super. onDestroy();
}
And when Activity is launched back, In onCreate check for the checkbox state in preference and if true enable the checkbox
SharedPreferences prefs = getSharedPreferences("private preference", Context.MODE_PRIVATE);
boolean isChecked = prefs.getBoolean("CheckboxData",false);
if(isChecked)
checkBoxView.setChecked(true)
Related
I wanted to add a `toast message` when clicked on a button and I added it. Now I want show it only **one time**, that means the toast message will **not show again** if clicked on the button after the first time **also after a restart of app**.
Please help me!
You can do it with SharedPreferences that you store in another class like Utility.java:
public class Utility {
public static SharedPreferences preferences(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public static Boolean hasSendToast(Context context) {
return preferences(context).getBoolean("Toast", false);
}
public static void setSendToast(Context context, Boolean bool) {
preferences(context).edit()
.putBoolean("Toast", bool).apply();
}
}
And use it with your Toast inside the onClickListener in your MainActivity.java like this:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = findViewById(R.id.button);
button.setOnClickListener(v -> {
if (!Utility.hasSendToast(getApplicationContext())) {
Toast.makeText(getApplicationContext(), "My Toast", Toast.LENGTH_SHORT)
.show();
Utility.setSendToast(getApplicationContext(), true);
}
});
}
}
You might want to look into https://developer.android.com/training/data-storage/shared-preferences. After the first click write a boolean into shared preferences to indicate the first click has happened. Next time the user clicks the button make sure to check if that boolean has been set and don't show the toast if that's the case.
You can use a boolean flag and store the value using Shared Preference.
btn.onClickListener {
if(!getToastShownStatusFromSharedPreference()) {
showToast()
changeToastShowsStatusToSharedPreference()
}
/* other operations */
}
Yes you can do that with SharedPreferences which is a pref manager in android. You can follow the below process:
Declare a boolean as like isFirstTime = true.
On the click of the button check boolean status, and if its true then fire the toast message and make isFirstTime = false.
That's it.
I have stored the checkbox value(check/uncheck) using shared preference,but I face problem while passing the action of checkbox on/after closing and reopening the app.Explantion: A button in different actvity hides/shows on clicking the checkbox(i.e check=shows & uncheck= hides) working correctly. when I close the app and reopen the checkbox stays checked but button is not appearing
checkbox code saved using shared preference
final CheckBox checkBox = (CheckBox) findViewById(R.id.add_fb);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
checkBox.setChecked(preferences.getBoolean("checked",false));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isCheckedValue = isChecked;
editor.putBoolean("checked", isChecked);
editor.apply();
}
});
}
I tried to implement onStart() for passing data by providing if-else condition
#Override
protected void onStart() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = preferences.edit();
super.onStart();
if(checkBox.isChecked()) {
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
This is where i am passing the data once the checkbox is checked
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
Instead of sending 'isCheckedValue' in 'onBubbleClickMethod'
try this -
in.putExtra("yourBoolName",preferences.getBoolean("checked",false));
What I'm trying to do is have a setting menu pull up when a button is pressed on my main menu (settings menu is implemented as a separate activity from my main). For simplicity's sake, assume that my main menu is blank except for 1 button that pulls up the settings menu. In the setting menu, there is one check box and one button "Done" that returns to the main activity.
How do I save a CheckBox's and load it (what should the code be, where should I put it, why, etc) ? I've tried googling it, and trying to replicate the results, but I can't seem to get it. 2 things have happened so far: nothing has saved, or my program crashes.
Once I have the information about the checkbox saved, how am I able to access this information from my main activity #I want to be able to run certain code based on if the user checked the box or not?
some results that I've landed on and tried:
How to save the checkbox state? - android
Saving Checkbox states
(Please keep in mind that I'm completely new to this)
public class Settings extends ActionBarActivity {
private static final String SETTING_CHECK_BOX = "SETTINGS";
private CheckBox cb;
//char boxChecked = '0';
#Override
protected void onCreate(Bundle savedSettings) {
super.onCreate(savedSettings);
cb = (CheckBox) findViewById(R.id.checkBox);
setContentView(R.layout.activity_settings);
cb.setChecked(isCheckedSettingEnabled());
}
private void setCheckedSettingEnabled(boolean enabled) {
PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(SETTING_CHECK_BOX, enabled).apply();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
private boolean isCheckedSettingEnabled() {
return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(SETTING_CHECK_BOX, false);
}
public void onPause() {
super.onPause();
// Persist the setting. Could also do this with an OnCheckedChangeListener.
setCheckedSettingEnabled(cb.isChecked());
}
public void clickedDone (View v) {
SharedPreferences settings = getSharedPreferences("SETTINGS", 0);
settings.edit().putBoolean("check",true).commit();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
So now my app doesn't crash anymore, but the state is not remembered (always unchecked when settings menu is open). I changed cb.setChecked(checkState) to cb.setChecked(TRUE), which didn't change anything (still always unchecked when settings menu is open). What is going on?
onSaveInstanceState() is only for persisting data for that instance of the Activity. Once that Activity has had finish() invoked, that state is no longer relevant. You need to write your settings to persistent storage. A simple storage solution for your case is SharedPreferences.
public class Settings extends ActionBarActivity {
// Create a constant for the setting that you're saving
private static final String SETTING_CHECK_BOX = "checkbox_setting";
private CheckBox mCheckBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mCheckBox = (CheckBox) findViewById(R.id.checkBox);
// Set the initial state of the check box based on saved value
mCheckBox.setChecked(isCheckedSettingEnabled());
}
#Override
public void onPause() {
super.onPause();
// Persist the setting. Could also do this with an OnCheckedChangeListener.
setCheckedSettingEnabled(mCheckBox.isChecked());
}
/**
* Returns true if the setting has been saved as enabled,
* false by default
*/
private boolean isCheckedSettingEnabled() {
return PreferenceManager.getDefaultSharedPreferences(this)
.getBoolean(SETTING_CHECK_BOX, false);
}
/**
* Persists the new state of the setting
*
* #param enabled the new state for the setting
*/
private void setCheckedSettingEnabled(boolean enabled) {
PreferenceManager.getDefaultSharedPreferences(this)
.edit()
.putBoolean(SETTING_CHECK_BOX, enabled)
.apply();
}
}
Once the state data is stored using onSaveInstanceState(), the system uses onRestoreInstanceState(Bundle savedInstanceState) to recreate the state.
If you are using onSaveInstanceState() You have to override the function onRestoreInstanceState() in the activity or use the saved state in onCreate(). I think it's better to use onRestoreInstanceState() , which can reduce the code in onCreate(), because the onSavedInstanceSate() is called only when the system
closes the app to make room for new applications to run. If you just want to save the checked state , use shared preference, no need of onSaveInstanceState().
//decalre in class
private CheckBox cb;
private SharedPreferences preferences ;
private SharedPreferences.Editor editor;
private boolean CHECKED_STATE;
#Override
protected void onCreate(Bundle savedSettings) {
super.onCreate(savedSettings);
setContentView(R.layout.activity_settings);
preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
editor = preferences.edit();
CHECKED_STATE = preferences.getBoolean("check", false);
cb = (CheckBox) findViewById(R.id.checkBox);
cb.setChecked(CHECKED_STATE);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
editor.putBoolean("check", isChecked);
editor.commit();
}
});
}
this code saves the state on clicking the check box.
To make it save the state on Back Press , add the following to your activity.
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
editor.putBoolean("check", cb.isChecked());
editor.commit();
}
for more details on Save instance state please refer this link.
I have one checkbox in my app which performes enabling\disabling bluetooth .. the problem is if I turn on\off from android setting(outside this app) then that checkbox is not updating like say if in app checkbox is checked means bluetooth is enable so now if I disable bluetooth from toggle or from system->settings and then go to my app then that checkbox is still checked ... how to get right state for that box ..(using fragment)
final BluetoothAdapter myBTadapter;
final Integer REQ_BT_ENABLE=1;
CheckBox enable;
myBTadapter=BluetoothAdapter.getDefaultAdapter();
enable=(CheckBox)vv.findViewById(R.id.cboxEnable);
enable.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
if(buttonView.isChecked()){
if(myBTadapter==null){
Toast.makeText(getActivity().getApplicationContext(),
"Device doesn't support Bluetooth",
Toast.LENGTH_LONG).show();
}
else{
if(!myBTadapter.isEnabled()){
Intent enableBtIntent = new Intent(BluetoothAdapter.);
startActivity(enableBtIntent);
}
}
}
else{
Toast.makeText(getActivity().getApplicationContext(),
"Disabling Bluetooth!!", Toast.LENGTH_LONG).show();
myBTadapter.disable();
}
}
});
Try this inside onResume() method:
if(myBTadapter.isEnabled()) {
enable.setChecked(true);
} else {
enable.setChecked(false);
}
I would like to know if the user is using the application for the first time. I am using SharedPreferences, but I am not sure if I have the right logic.
How can I set my isFirstLaunched boolean to true when the user first launches, and then immediately set to false after work has been done?
protected void onStart() {
super.onStart();
if(isFirstLaunch()){
populateDefaultQuotes();
//Save the preferences, isFirstLaunch will now be false
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isFirstLaunch", false);
editor.commit();
}
setupUI();
checkOrientation();
restoreCache();
}
private void populateDefaultQuotes(){
System.out.println("!!!!!! FIRST TIMER !!!!!!");
}
private boolean isFirstLaunch() {
// Restore preferences
SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
boolean isFirstLaunch = settings.getBoolean("isFirstLaunch", false);
return isFirstLaunch;
}
Replace the false argument in getBoolean() by true, then the logic will fit.
boolean isFirstLaunch = settings.getBoolean("isFirstLaunch", true);
This will return true if there is no such setting.
you can register a BroadcastReceiver to listen for Intent.ACTION_PACKAGE_FIRST_LAUNCH
http://developer.android.com/reference/android/content/Intent.html#ACTION_PACKAGE_FIRST_LAUNCH