Android Save and check, radio button - java

Sorry for my bad english.
I have 2 classes,
1 MainActivity.java (Standard)
2 settings.java (for settings)
I have a RadioGroup with 5 Radiobuttons.
I save the state of the radio buttons as follows (in to settings.java class):
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences settings = getSharedPreferences("status", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("blue", blue.isChecked());
editor.putBoolean("orange", orange.isChecked());
editor.putBoolean("purple", purple.isChecked());
editor.putBoolean("grey", grey.isChecked());
editor.putBoolean("green", green.isChecked());
editor.commit();
}
public void loadSettings () {
SharedPreferences settings = getSharedPreferences("status", 0);
royalBlue.setChecked(settings.getBoolean("blue", false));
orange.setChecked(settings.getBoolean("orange", false));
purple.setChecked(settings.getBoolean("purple", false));
titan.setChecked(settings.getBoolean("grey", false));
eighties.setChecked(settings.getBoolean("green", false));
}
the status of the radio buttons is saved successfully. Even after a restart of the app the radio button is saved.
I would like now when the RadioButton orange (or other) is selected, the ImageButton will change my image. I would like to make in the MainActivity.
I have tried it in the Main Activity so but I always get a NullPoinException:
Code from the Main ...
private settings load = new settings();
...
...
public void change (){
if (load.orange.isChecked()){
imBuOn.setImageResource(R.drawable.orange);
}
as I said I can so unfortunately unable to access the status of the radio button.
Do I need to maybe use PreferenceManager? how shall I put it best?

You don't need to create an instance of the settings class and fetch the value of the checkBox. Instead, you should just use the same code as given in the loadSettings method since you are just accessing the SharedPreferences file.
So, in your MainActivity, just run this
private void checkAndSetImage()
{
SharedPreferences settings = getSharedPreferences("status", 0);
if(settings.getBoolean("orange", false))
{
imBuOn.setImageResource(R.drawable.orange);
}
}
Just call this function to wherever applicable.

Related

How to save condition of button after closing app?

This is code of button:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setEnabled(false);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
button.setEnabled(true);
}
},120000);
}
});
I know that i need to create a sharedpreferences, but I didn't understand how to save condition of button which have a timer, because i know how to save without ussing handler.
How can i do this?
You'll have to use shared preference to save the state. Then, while creating the view of you fragment or activity, you should check the value you saved with shared preference and set the button state accordingly.
Permit me, please, to answer in Kotlin, maybe you or your IDE can do the translation.
To save your button state to shared preference, define this function;
fun setButtonState(context: Context, buttonEnabled: Boolean) {
PreferenceManager.getDefaultSharedPreference(context).edit()
.putBoolean("button", buttonEnabled).apply()
}
Then to get your saved button state from shared preference, define this function;
fun getButtonState(context: Context): Boolean {
return PreferenceManager.getDefaultSharedPreference(context)
.getBoolean("button", false)
}
In your onCreateView set the button state in accordance to your saved value.
val buttonEnabled = getButtonState(requireContext())
button = view.findViewById(R.id.button)
button.isEnabled = buttonEnabled
Then toggle the saved state in shared preference like so:
button.setOnClickListener {
button.isEnabled = false
setButtonState(requireContext(), false)
Handler(Looper.getMainLooper()).postDelayed({
button.isEnabled = true
setButtonState(requireContext(), true)
}, 120000)
}
I hope this helps. :)

How to make radio buttons display a text in another activity when clicked in android studio?

I have 6 options that the user can select from and a button that takes them to the next page when clicked. I have two pages like this. After one choice from each page is selected, I would like to display certain text depending on the radio buttons clicked previously, in another activity. How can I do this in java in android studio?
If you are controlling the FragmentManager you can just pass the options as an argument to the next Fragment's constructor otherwise, you can save everything in a static variable (as long as no Views are in there, so don't store the radio buttons there) and access that variable from outside.
Like this:
public class MyFragment {
public static boolean isRadioButtonXPressed = false; //change to true if it's pressed by default
public void onCreate(...) {
radioButtonX.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
isRadioButtonXPressed = checked;
}
});
}
}
//from the other fragment
public class MyFragment2 {
public void onCreateView(...) {
if (MyFragment.isRadioButtonXPressed) {
//it's been pressed
} else {
//it's not been pressed
}
}
}
There are many different ways.
As you are using activity, you can use Intent to pass data. Here is a sample:
Intent page = new Intent(FirstActivity.this, SecondActivity.class);
page.putExtra("key", "This is my text");
startActivity(page);
For getting the value on Second Activity onCreate() method:
String value = getIntent().getStringExtra("key");

Save state of Button in activity Android

I have two buttons(button1, button2) in my activty. botton1 is 'Enabled'(true) , while the other one isn't.
When I click on button1, button2 becomes 'Enabled'. I want to record this activity in this state for the next utilization of my application.
You can save state in sharedPrefrences, try this
SharedPreferences prefs = getSharedPreferences("Your preference name here", MODE_PRIVATE)
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
b2.setEnabled(true);
prefs.edit().putBoolean("b2enabled", true).commit();//saving State here
}
});
And now where you want to use this state simple get the state as.
Boolean b2state= prefs.getBoolean("b2enabled", false); //false is the default value
And if you want to enable or disable button on result do
if (b2state){
b2.enabled(true);
}
else{
b2.enabled(false);
}
Well, you can use the help of a data storage option. For a simple task like this,
shared preference is enough.
use something like this to store the state change.
function setState(boolean state){
SharedPreferences sharedPref =this.getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("state",state);
}
you can retrieve the data at anytime (usually in in the beginning) like this. Note that the second argument serves the default value.
int state=this.getPreferences(Context.MODE_PRIVATE).getBoolean("state",false);
Hope this helps.

Saving a checkbox's state, and then loading it

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.

Adding dynamic checkbox preferences in Android, and display them in preference screen?

I want to implement functionality where user will be able to select which group of items to be displayed using checkbox shared preferences. To be precise I will read checked items from the preferences and display.
Here is my preferences class
public class Preferences extends PreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//One way to add default preferences
//addPreferencesFromResource(R.xml.prefs);
//For now I prefer this
setPreferenceScreen(defaultPref());
}
// The first time application is launched this should be read
private PreferenceScreen defaultPref() {
PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this);
CheckBoxPreference checkboxPref = new CheckBoxPreference(this);
checkboxPref.setKey("1");
checkboxPref.setTitle("SomeRandomStuff");
root.addPreference(checkboxPref);
return root;
}
public showAllPreferences () {
// TO SHOW ALL THE PREFERENCES BUT NOT SURE HOW TO DISPLAY THEM
}
}
Now I cannot understand how do I add more preferences dynamically and display them in preference screen.
Here is the main activity class
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.main);
}catch (Exception e) {
e.printStackTrace();
}
exView = (ExpandableListView) findViewById(R.id.expandableListView1);
// STUFF TO ADD IN PREFERENCES
editText = (EditText) findViewById(R.id.editText1);
//BUTTON TO ADD PREFERENCES.(SEARCH TERM IS IDENTIFIED AND ADDED TO PREF)
addButton = (ImageButton) findViewById(R.id.imageButton1);
// BUTTON TO DISPLAY PREFERENCES
prefButton = (ImageButton) findViewById(R.id.imageButtonPref);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final SharedPreferences.Editor editor = settings.edit();
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
PrefObject obj = new PrefObject();
String key = Integer.toString(i);
String title = editText.getText().toString();
//prefArray.add(obj);
editor.putString(key, title);
editor.commit();
i++
}
});
prefButton.setOnClickListener(new OnClickListener() {
// This method should show the preferences activity with new data
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Main.this, Preferences.class);
startActivity(intent);
// I know how to call the intent but I am not sure if
// how to read the saved contents and display it
Preferences pref = new Preferences();
pref.showAllPreferences();
}
});
AFAIK, there is no "visibility" option for preferences, which kinda makes sense when you think it's all just a ListView.
See [1]. For what I see, you could do something like this:
PreferenceScreen screen = this.getPreferenceScreen();
// Use "1" since you're using "1" to create it.
CheckBoxPreference ckbox = (CheckBoxPreference) this.findPreference("1");
screen.removePreference(ckbox);
To recreate, you could do this [2]:
screen.addPreference(ckbox);
Additionally, remember to create your preference using the setOrder(int order) so that when you recreate, it will be recreated in the proper position.
As you can see, it could be worth to keep a global reference to the preference to make it easier and faster.
Of course, I don't need to tell that you should integrate that logic into your CheckboxPreference listener. See this answer by nobody else than Reto Meier himself to see a good way of doing it (it's a checkbox, too). There he registers a listener to the whole screen and checks which preference triggered the listener, but you can do it simpler (but more verbose later on) by just setting its setOnPreferenceChangeListener.
*edit: I see that you're also using a button to add the preference. You can also implement the same logic above into the button itself. It all depends if you want to do this using a checkbox or a button.
Finally, it could be worth to just set the enabled state, unless you are doing something like "see advanced preferences" or something worth to keep novice users away from doing dangerous stuff to your app. But generally the enable states work better for user experience, IMHO.
I hope this answers your question.

Categories

Resources