Android - remember me function for saving radio buttons in Java - java

I am new to Android development and I am wondering if there is a way to have some sort of remember me function where it allows a user to have an option whether to save the current state of radio buttons.... a bit like a remember me function on a login apart from using a set of radio buttons instead....any help will be appreciated!
Here is my code:
#Override
/*
* Holding the data for the radio buttons from the xml file
*/
RadioGroup gender = (RadioGroup) findViewById(R.id.question1);
gender.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
switch (checkedId) {
case R.id.answer1A:
ans1 = 1;
break;
case R.id.answer1B:
ans1 = 2;
break;
}
}
});

To obtain shared preferences, use the following method In your Code:
SharedPreferences _prefs = this.getSharedPreferences(
"values_to_remember", Context.MODE_PRIVATE);
To read preferences:
int ansA = "ans1";
int value = _prefs.getInt(ansA, 1(default value));
To edit and save preferences
_edit().putInt(ansA , 1).apply();

private RadioButton button;
private SharedPreferences preferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferences=getSharedPreferences("check", MODE_PRIVATE);
button=(RadioButton)findViewById(R.id.question1);
button.setChecked(preferences.getBoolean("set", false));
button.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences.Editor editor=preferences.edit();
editor.putBoolean("set", isChecked);
editor.commit();
}
});
}
You will have use a sharedpreference. And store the state of radiobutton in it.

Related

.setChecked() isn't setting the state of radio button

I'm creating a security settings part in my app.
There are 3 radio buttons that allow the user to choose between a passcode, TouchID or nothing. All radio buttons are unchecked by default. When clicking on a radio button (e.g. to use passcode), the code checks to see if the user has set up a passcode. If the user hasn't, a dialog is shown and the radio button remains unchecked. The user then goes and sets up a passcode (setUpPasscode button).
Once set up, the passcode activity closes with the return case '2' and the radio button with the passcode option should be checked. It isn't however. When I re-launch the application, the button is checked though. It somehow isn't checked immediately after finishing the previous activity but it is technically checked. What am I doing wrong?
public class SecuritySettings extends AppCompatActivity
{
TextView goBackToSettings;
Button setUpPasscode;
Button setUpTouchID;
RadioButton usePasscodeSelection;
RadioButton useTouchIDSelection;
RadioButton useNeitherSelection;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Dialog myDialog;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.security_settings);
goBackToSettings = (TextView) findViewById(R.id.closeSettingsButtonID);
setUpPasscode = (Button) findViewById(R.id.setUpPasscodeButtonID);
setUpTouchID = (Button) findViewById(R.id.setUpTouchIDButtonID);
usePasscodeSelection = (RadioButton) findViewById(R.id.usePasscode);
useTouchIDSelection = (RadioButton) findViewById(R.id.useTouchID);
useNeitherSelection = (RadioButton) findViewById(R.id.useNothing);
myDialog = new Dialog(this);
//load state of radio buttons
loadRadioButtons();
// go back to main settings page
goBackToSettings.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent goBackToMainSettings = new Intent(getApplicationContext(), AppSettings.class);
goBackToMainSettings.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(goBackToMainSettings);
finish();
}
});
//Open new activity for setting passcode
setUpPasscode.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setUpPasscodeActivity = new Intent(getApplicationContext(), SetupPasscode.class);
startActivityForResult(setUpPasscodeActivity, 2);
}
});
// Open new activity for setting up TouchID
setUpTouchID.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Intent setupTouchIDActivity = new Intent(getApplicationContext(), SetupTouchID.class);
startActivityForResult(setupTouchIDActivity, 1);
}
});
// when clicked, all other buttons become unchecked and the state of the buttons are saved
usePasscodeSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForPasscode = doesUserHavePasscode();
// If true, user has a passcode setup
if (bCheckForPasscode)
{
usePasscodeSelection.setChecked(true);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up a passcode to enable this option.");
}
}
});
useTouchIDSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
boolean bCheckForTouchID = doesUserHaveTouchIDSetup();
// If true, user has TouchID setup
if (bCheckForTouchID)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(true);
useNeitherSelection.setChecked(false);
saveRadioButtons();
}
else
{
//No passcode detected for user
// Load previous radio button configuration since the selection wasn't valid
loadRadioButtons();
NoOptionSetPopup(null, "You must set up TouchID to enable this option.");
}
}
});
useNeitherSelection.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(true);
saveRadioButtons();
}
});
}
// Open sharedpreferences and get the value that was saved there after setting up passcode using the same key 'string'
public boolean doesUserHavePasscode()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
String checkHashString = sharedPreferences.getString("hashed_password", null);
if (checkHashString == null)
{
return false;
}
else
{
return true;
}
}
// Open sharedpreferences and get the value that was saved there after setting up TouchID using the same key 'string'
public boolean doesUserHaveTouchIDSetup()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
boolean bDoesUserHaveTouchIDSetup = sharedPreferences.getBoolean("doesUserHaveTouchIDSetup", false);
return bDoesUserHaveTouchIDSetup;
}
public void NoOptionSetPopup(View v, String message)
{
TextView closePopup;
TextView contents;
myDialog.setContentView(R.layout.no_option_setup_popup);
closePopup = (TextView) myDialog.findViewById(R.id.closePopupButtonID);
contents = (TextView) myDialog.findViewById(R.id.theMessageID);
contents.setText(message);
closePopup.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
//Close popup
myDialog.dismiss();
}
});
myDialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
myDialog.show();
}
// Callback method to get the boolean from SetupPasscode/SetupTouchID activity & override the method
// What is being done here is that after a passcode/TouchID has been setup, we automatically assume that the newly set-up authentication will want to be used by the user.
// The values being returned from the activities only happen when they're successfully done (passed all validation checks).
// We then automatically make the corresponding radio button selected (if passcode setup, then select the 'use passcode on startup' radio button)
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
{
// Case for returning from SetupPasscode class
case 2:
// fetch the boolean value
boolean isDone = data.getBooleanExtra("isDone", false);
usePasscodeSelection.setChecked(isDone);
useTouchIDSelection.setChecked(false);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
// Case for returning from SetupTouchID class
case 1:
// fetch the boolean value
boolean isTouchIDSetup = data.getBooleanExtra("isTouchIDDone", false);
usePasscodeSelection.setChecked(false);
useTouchIDSelection.setChecked(isTouchIDSetup);
useNeitherSelection.setChecked(false);
saveRadioButtons();
loadRadioButtons();
break;
default:
throw new IllegalStateException("Unexpected value: " + requestCode);
}
}
public void saveRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = sharedPreferences.edit();
editor.putBoolean("usePasscodeOption", usePasscodeSelection.isChecked());
editor.putBoolean("useTouchIDOption", useTouchIDSelection.isChecked());
editor.putBoolean("useNeitherOption", useNeitherSelection.isChecked());
}
public void loadRadioButtons()
{
sharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);
usePasscodeSelection.setChecked(sharedPreferences.getBoolean("usePasscodeOption", false));
useTouchIDSelection.setChecked(sharedPreferences.getBoolean("useTouchIDOption", false));
useNeitherSelection.setChecked(sharedPreferences.getBoolean("useNeitherOption", false));
}
}
I would suggest to overload the onResume method and checking the state of your radio buttons as that will be the last control where the flow will leave your activity.

How can I persist the string/int value in EditText when i relaunch my application?

In my Android activity, I have one EditText, a '+' button, a '-' button, 'Save' button and 'Load' button. When I press '+', the value in EditText increases by 1, similarly on pressing '-' value decreases by 1. I used SharedPreferences to save the data when I click on 'Save'. When I click 'Load', I want to reload this data onto the EditText field.
Now the problem is, when I completely exit the application (even from recently used apps), and click 'Load' on relaunching it, the saved number doesn't appear. I included the onClick() action for the 'Load' method in onRestart() method. It still doesn't work. What am I missing here? I even tried out all other suggestions for the similar questions asked previously here.
Also, is it really onRestart() or onRestoreInstanceState() ?
public class MainActivity extends Activity {
Button btn1;
Button btn2;
Button btn3;
Button btn4;
EditText scoreText;
int counter = 0;
TextView textTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.add);
btn2 = (Button)findViewById(R.id.subtract);
btn3 = (Button)findViewById(R.id.save);
btn4 = (Button)findViewById(R.id.load);
scoreText = (EditText)findViewById(R.id.total);
textTitle = (TextView)findViewById(R.id.title);
btn1.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter++;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.GREEN);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
counter=counter-1;
scoreText.setText(Integer.toString(counter));
scoreText.setBackgroundColor(Color.RED);
}
});
btn3.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
//store data using sharedprefernces
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
//Edit method allow to write the data in sharedpreferences
editor.putString("count",scoreText.getText().toString());
//For commit changes commit() method is used
editor.commit();
Toast.makeText(getApplicationContext(),"Data Saved",Toast.LENGTH_SHORT).show();
}
});
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
// scoreText.setText(strcount);
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
#Override
protected void onRestart(Bundle savedInstanceState){
super.onRestart(savedInstanceState);
btn4.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("Data", Context.MODE_PRIVATE);
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
if (strcount.equals(""))
{
Toast.makeText(getApplicationContext(), "Data Was Not Found", Toast.LENGTH_SHORT).show();
}
else
{
scoreText.setText(strcount);
}
scoreText.setBackgroundColor(Color.YELLOW);
}
});
}
You using using count as key to save the value
editor.putString("count",scoreText.getText().toString());
but using name as key to retrieve the value so you need to use count key while getting the previously stored data so use
sharedPreferences.getString("count",scoreText.getText().toString());
instead of
sharedPreferences.getString("name",scoreText.getText().toString());
You are using different keys to save and retrieve the data from SharedPrefernces.
editor.putString("count",scoreText.getText().toString());
String strcount=sharedPreferences.getString("name",scoreText.getText().toString());
You should be using the same key in both the cases otherwise it would return default value which is the text in TextView and that would be empty at the start of the app, you just need to change the key and that would do the trick for you.
Just change the below line like it is mentioned
String strcount=sharedPreferences.getString("count",scoreText.getText().toString());

How to save states of multiple dynamically generated checkboxes in a list view? (Android Java)

I have an Activity that looks like this - the length of the list view is dynamic and can change;
Now, I have declared and initialized checkboxes based on the length of the array.
I need to save the states of these boxes when the user clicks on "Save". How do I achieve this? I wrote the following code, but I get no input, i.e. even though the checkboxes are initialized, I don't think the activity knows which checkbox declaration is for which checkbox on the activity. Please help - thanks!
cbs = new CheckBox[length];
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
}
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DoOnBtnClick(v);
}
});
}
public void DoOnBtnClick (View v) {
for(int i = 0; i < cbs.length; i++){
if(cbs[i].isChecked()){
selectedCheckboxes.add(toInt(cbs[i].getTag()));
Log.e("GET TAG",Integer.toString(toInt(cbs[i].getTag())));
}
}
}
you can use sharedPreferences to store and retrieve checkbox state data
Initialize variables first:
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
Now in your onCreate() after all checkbox are initialized use setOnCheckedChangeListener
Now you can load data from sharedpreferences using this:
public void Load_checklist() {
SharedPreferences shared = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
for(int i = 0; i < cbs.length; i++){
if (shared.getString(Integer.toString(i), "").equals("1")) {
cbs[i].setChecked(true);
}else{
cbs[i].setChecked(false);
}
}
}
finally your onCreate method should look like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_name);
int array_length=jArray.length(); //checkbox size
//layout where you want to dynamically add checkboxes
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.lyout);
Load_checklist();
for(int c=0; c<jArray.length();c++){
CheckBox chk=new CheckBox(this);
chk.setId(c++);
chk.setText("Click to add values");
chk.setTextColor(Color.GRAY);
chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
String s="x"+buttonView.getId();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
switch(buttonView.getId()){
case 1: // do something on 1st checkbox
if (isChecked) {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "1");
editor.commit();
} else {
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Integer.toString(c), "0");
editor.commit();
}
break;
case 2: //do something on 2nd checkbox
break;
//And SO ON for all checkboes
}
}
});
linearLayout.addView(chk);
}
}
N.B: If SetId(Int) is not working then you can use setTag(int) instead.
If a CheckBox's Tag should represent its index in the list, you should set that tag when you are instantiating them.
for (int i=0;i<length;i++){
cbs[i] = new CheckBox(ThisActivity.this);
cbs[i].setTag(i);
}
I would not recommend this approach if you expect to have a variable amount of checkboxes due to the performance implications. Instead, consider using a RecyclerView with a backing list of model objects representing the state of your checkboxes.
https://developer.android.com/reference/android/support/v7/widget/RecyclerView.html

Shared Preference saving the checkbox action

I was able to store the value of checkbox using shared preference but I was not able to save the action its meant to do.The action what i need is when checkbox is checked a button should display,if checkbox is unchecked button should not display(hiding/showing button is done in different activity). So what I did was i passed the value isCheckedValue = isChecked; under if/else condition
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();
if(checkBox.isChecked()) {
isCheckedValue = isChecked;
editor.putBoolean("checked", true);
editor.apply();
}else{
editor.putBoolean("checked", false);
editor.apply();
}
}
});
if chkbox is checked the value will pass using intent in onBubbleClick using the boolean passing data in.putExtra("yourBoolName", isCheckedValue ); you could notice it in below bunch of code
private void addNewBubble() {
BubbleLayout bubbleView = (BubbleLayout)LayoutInflater.from(MainActivity.this).inflate(R.layout.bubble_layout, null);
bubbleView.setOnBubbleRemoveListener(new BubbleLayout.OnBubbleRemoveListener() {
#Override
public void onBubbleRemoved(BubbleLayout bubble) {
finish();
System.exit(0);
}
});
bubbleView.setOnBubbleClickListener(new BubbleLayout.OnBubbleClickListener() {
#Override
public void onBubbleClick(BubbleLayout bubble) {
Intent in = new Intent(MainActivity.this, PopUpWindow.class);
in.putExtra("yourBoolName", isCheckedValue );
startActivity(in);
}
});
bubbleView.setShouldStickToWall(true);
bubblesManager.addBubble(bubbleView, 60, 20);
}
How it works: At the very beginning the button is not displayed until the checkbox is clicked, the button gets displayed once the checkbox is checked and never gets hidden even after unchecked the checkbox.
How it's meant to work The button should display if the checkbox is checked and button should hide if the checkbox is unchecked.
In your if-else block, you aren't really updating the value of isCheckedValue in false condition. So, that needs to be fixed. I also refactored your code a bit. Try the following:
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();
}
});

How to save the state of the checkbox when it is checked and a button pressed

Aim is to save the background color of a textview whenever a checkbox is checked and a button is pressed while it will revert back to its normal state when redoing it.
I know that to do that i can use shared preferences but somehow it doesn't work (NOT SAVED). Here is the codes that i have used (checkbox is created programtically not though xml)
status=(Button)findViewById(R.id.status);
CheckBox checkbox = new CheckBox(myContext);
tr.addView(checkbox);
checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {
// TODO Auto-generated method stub
if (isChecked){
status.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
//myEditor.putInt("backColor", Color.LTGRAY);
//tr.setBackgroundColor(Color.LTGRAY);
mySharedPreferences=getSharedPreferences(MYPREFS,0);
SharedPreferences.Editor myEditor;
myEditor=mySharedPreferences.edit();
final int backColor=mySharedPreferences.getInt("color", Color.LTGRAY);
tr.setBackgroundColor(backColor);
myEditor.putInt("color", backColor);
myEditor.commit();
}
});
}
}
}
im not sure of what you are trying to say, but you could try this.
boolean check = :JCheckBox reference:.isSelected();
if JCheckBox reference was checkBox, then it would look like this.
boolean check = checkBox.isSelected();
method returns a boolean value.
How i would do it:
You have your checkbox set up (i will call it checkBox) And
you have your color editor (it will be colorEditor)
So first you need to crate two entries in the SharedPreferences: DEFAULT_COLOR and CURRENT_COLOR
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("DEFAULT_COLOR", 0xFFFFFFFF); // we will not touch this later
editor.putInt("CURRENT_COLOR", 0xFFFFFFFF); //set to DEFAULT, will change this.
editor.commit();
Now now in the onCheckedChanged you simply need to do this:
public void onCheckedChanged(CompoundButton checkBox, boolean isChecked)
{
SharedPreferences preferences = ...; //just get the SharedPref. object
SharedPreferences.Editor editor = preferences.edit();
int color = preferences.getInt("DEFAULT_COLOR", -1); //get the default color
// change it if the CheckBox is checked
if(isChecked)
color = colorEditor.getColor(); //get the color from wherever you want
editor.putInt("CURRENT_COLOR", color);
editor.commit();
//set the color as background.
}
Also don't forget to set the background color to the "CURRENT_COLOR" from your SharedPreferences every time you start the app!
Also it's a good practice to add every View programmatically OR from XML, becuse it's a big soure of errors!
package com.android.app;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.app.Activity;
import android.content.SharedPreferences;
public class MainActivity extends Activity {
CheckBox cb;
Button save,load;
SharedPreferences sp;
public static String filename=("Folder");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cb=(CheckBox)findViewById(R.id.checkBox1);
save=(Button)findViewById(R.id.bsave);
load=(Button)findViewById(R.id.bload);
sp=getSharedPreferences(filename,0);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean b=cb.isChecked();
SharedPreferences.Editor editor=sp.edit();
editor.putBoolean("str",b);
editor.commit();
finish();
}
});
load.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
sp=getSharedPreferences(filename,0);
boolean bool=sp.getBoolean("str",false);
cb.setChecked(bool);
}
});
}
}
I have tested this; it works.

Categories