Android RadioButton Confirm Selection - android

In my Android Application it's required to give a notification(warning) message before user change Radio Group Selection.
Basically I am trying to give a dialog message (that have warning message and YES/NO buttons to confirm change) when user click any other radio button within that Radio groiup.
If user presses YES then to change readio button selection with what user wanted to change, otherwise (if press NO) to select back with what was selected before.
I don't see any option in onCheckedChanged method when listen to OnCheckedChangeListener. What would be the best way to do this. Thanks
EDITS
I'm providing the warning message from a Dialog within onCheckedChanged method with option to Confirm the change (with YES/NO buttons). Problem is when user don't want the new selection after seeing the warning, I need a way to know the prevoiusly selected Radio Button to revert user's new selection.
public void onCheckedChanged(RadioGroup group, int checkedId)
The above method provides "checkedId" but how to know which Radio Button had selected before. It's required when user want to Cancel change..
Can do this by tracking the ealier selection defining a class level variable to hold old Radio button ID or some other logic like that. But there should be a straight forward way in Radio group to cancel new selection (by selecting old one back). I looked for beforeRadioCheckChange Type listener but didn't manage to find

You can store selected button before (when you actually set which one of radio buttons should be checked initially):
int selectedButton = mRadioGroup.getCheckedRadioButtonId();
And update it inside onCheckedChanged callback:
selectedButton = group.getCheckedRadioButtonId();
when user confirms change. Otherwise return checked state to the last selectedButton.

there is no a method in RadioGroup that enables you to revert your action, however you can easily achieve this by holding the id of selected RadioButton in an outside variable, and use it to revert your changes back:
RadioGroup radio;
static int buttonChecked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
radio = (RadioGroup) findViewById(R.id.radioGroup);
buttonChecked = radio.getCheckedRadioButtonId(); // be sure to get the checked button id first time before assigning the onCheckedChange
radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Raise Dialog
if(yes){ // User confirmeed
buttonChecked = checkedId;
}else{ // User refused
if(buttonChecked != -1) // to prevent app from crashing if nothing is already selected
radio.check(buttonChecked);
else
radio.clearCheck();
}
}
});
}

Related

null object reference in Android

I am trying to work on radio groups. I have an ok button which when clicked selects one item from four inflated radio button groups. My problem is that, when the user does not select an option from one of the groups, I have a null pointer exception.
Here is my selection code
private void getSelectedValuesAdults()
{
rl=(RelativeLayout)findViewById(R.id.activity_selections);
int id1 = ((RadioGroup)findViewById(R.id.KSradioGrp)).getCheckedRadioButtonId();
int id2 = ((RadioGroup)findViewById(R.id.KTradioGrp)).getCheckedRadioButtonId();
int id3 = ((RadioGroup)findViewById(R.id.KDradioGrp)).getCheckedRadioButtonId();
int id4 = ((RadioGroup)findViewById(R.id.KSoradioGrp)).getCheckedRadioButtonId();
stringChoice[0]= ((RadioButton)findViewById(id1)).getText().toString().contains(generalKid[0].getName())==true?generalKid[0].getName():generalKid[1].getName();
stringChoice[1]= ((RadioButton)findViewById(id2)).getText().toString().contains(generalKid[2].getName())==true?generalKid[2].getName():generalKid[3].getName();
stringChoice[2]= ((RadioButton)findViewById(id3)).getText().toString().contains(generalKid[4].getName())==true?generalKid[4].getName():generalKid[5].getName();
stringChoice[3]= ((RadioButton)findViewById(id4)).getText().toString().contains(generalKid[6].getName())==true?generalKid[6].getName():generalKid[7].getName();
genCost[0]= ((RadioButton)findViewById(id1)).getText().toString().contains(generalKid[0].getName())==true?generalKid[0].getCost()+5:generalKid[1].getCost()+5;
genCost[0]= ((RadioButton)findViewById(id2)).getText().toString().contains(generalKid[2].getName())==true?generalKid[2].getCost()+5:generalKid[3].getCost()+5;
genCost[0]= ((RadioButton)findViewById(id3)).getText().toString().contains(generalKid[4].getName())==true?generalKid[4].getCost()+5:generalKid[5].getCost()+5;
genCost[0]= ((RadioButton)findViewById(id4)).getText().toString().contains(generalKid[6].getName())==true?generalKid[6].getCost()+5:generalKid[7].getCost()+5;
}
The Ok button jumps to the method above. I have used if(id1==-1||id2==-1||id3==-1||id4==-1) callDialogMessage() just before the assignment to stringChoice[0] where callDialogMessage() is a message that lets you know you have not selected from a radio group but my app still crashes. What can I do? Any help will be highly appreciated
On click of OK button get selected radio button Id using radio group .You can refer the below code.
int selectedId =radioButtonGroup.getCheckedRadioButtonId();;
// find the radiobutton by returned id
RadioButton radioButton = FindViewById<RadioButton>(selectedId);
if(radioButton !=null)
{
//do things here
}

How to get CheckBox value present in RadioGoup in Android?

New to Android,
I am creating a question Answer App. So I want to get the value of checkBoxes.
I know how to get value of radio button present in Radio Group.
But I want to know is it good practice to keep checkBixes in RadioGroup and how to get the Checkboxes value?
What do you mean by getting CheckBox value? You can get the state (checked or not checked) and you can also get the text label for the CheckBox itself (getText()).
As for keeping them in a RadioGroup, it will depend largely on your use case (when grouped, the user might expect that only one CheckBox at the time can be checked). If you were to implement RadioGroup, you will have to implement a listener and then determine which CheckBox was checked. For that you can look at the accepted answer on this closely related question here.
Here is how you can get the Text of the CheckBox that was checked/unchecked:
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
CheckBox checkBox = (CheckBox)findViewById(checkedId);
//here you can check if it was checked or not, including the text
String text = checkBox.getText().toString();
boolean isChecked = checkBox.isChecked();
}
I hope this sheds some light.
Unfortunately as you would expect to utilize radioGroup's getCheckedRadioButtonId() for radio buttons, there is no such thing for check boxes. There are many ways to do this but I think the simplest and cleanest way would be the following:
For CheckBoxes
// Define one listener to use it for all of your CheckBoxes:
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// You can also use the buttonView.isChecked() instead of isChecked parameter too : if(ButtonView.isChecked)..
if(isChecked) {
// Do stuff with this checkBox for example:
String stringToShow = buttonView.getText();
}
}
};
// Reference your CheckBoxes to your xml layout:
CheckBox checkBox1 = findViewById(R.id.checkBox1);
CheckBox checkBox2 = findViewById(R.id.checkBox2);
// and many more check boxes..
/* Set the above listener to your Check boxes so they would
notify your above piece of code in case their checked status
changed:*/
checkBox1.setOnCheckedChangeListener(listener);
checkBox2.setOnCheckedChangeListener(listener);
// and many more check boxes..

Android RadioGroup checkedId out of bound

I am doing an app in which I must generate checkboxes with certain base values for the initial selected item and then change it's value. Nothing very complicated there.
My problem is when i reset the layout, I create a new RadioGroup with new RadioButtons and a new OnCheckedChangeListener for the RadioGroup. But when I click on a checkbox after resetting the UI, the checkId coming from the listener outputs something too big out of the bound of my RadioGroup.
Here's my code. I won't show the reset part but mainly I call removeAllViews() and then generate the layout again.
final RadioGroup optGroup = new RadioGroup(getActivity());
optGroup.setOrientation(LinearLayout.HORIZONTAL);
for(int itemNo = 0; itemNo < cell.getList().countItems(); itemNo++){
RadioButton rButton = new RadioButton(getActivity());
rButton.setText(cell.getList().getItem(itemNo).getLabel());
optGroup.addView(rButton);
if(cell.getSelectedListItem().getLabel().equals(cell.getList().getItem(itemNo).getLabel())){
optGroup.check(itemNo+1);
}
}
optGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
cell.selectListItem(String.valueOf(checkedId));
}
});
linearLayout.addView(optGroup);
When I log my input, before resetting the UI, the output ranges from 1 to 3 (I have 3 checkboxes) and after the reset, it ranges from 4 to 6.
EDIT The initial check only works for the first time too, like if the range of the 3 displayed was from 4 to 6 the second time.
Thanks!
You should set the radioButton ID
rButton.setId(itemNo);
But make sure not to use 0 as Id.
Since each RadioButton Id must be unique, I guess OS is keeping track of what autogenerated Ids were used (1-3) for the first run. Then after reset, it goes with 4-6, (resumed count from 3)

100 Buttons and only 1 Active

I have one activity and here i have 100 buttons, i want that when i press Button 1 then press another Button the Button 1 should get unpressed.
i know i can make this with
if(Button1.isPressed()) {
Button2.setPressed(false);
Button3.setPressed(false);
Button4.setPressed(false);
Button5.setPressed(false);
Button6.setPressed(false);
Button7.setPressed(false);
Button8.setPressed(false);
......................... }
else { do nothing }
.... BUT!
it's too much code
Coders will kill me or will just laugh on me.
any ideas?
maybe there is a way to unpress the all buttons from the activity?
Not the prettiest solution ever, but you could make an OnClickListener like this:
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
ViewGroup parent = (ViewGroup) v.getParent();
for (int i = 0; i < parent.getChildCount(); i++) {
View current = parent.getChildAt(i);
if (current != v && current instanceof Button) {
((Button) current).setPressed(false);
}
}
((Button) v).setPressed(true);
}
}
and attach it to all of your buttons.
Then, whenever a button is clicked, it will iterate over all views that are in the same layout (or actually, view group) as the clicked button, and, for any of those views that are buttons except for the clicked button, it will call setPressed(false).
Note that this only works out of the box if all the buttons are in the same layout. If they are in nested layouts, you will have to adapt it a little.
Off topic: What do you need 100 buttons for? That's a lot of buttons. You may want to redesign your user interface
Ok so instead of looping through all the buttons on over and over again when one button is pressed, you can just store a variable which stores the button number of the button that was last pressed. Now, when the second button is pressed, disable the button that was pressed earlier, you get its index from the saved variable, enable the button that was pressed and store its index in the variable.
Heres an example pseudo code to give you and idea:
int buttonLastPressed = 0;
void onButtonClick(Button buttonPressed){
if(buttonLastPressed != 0){
disableButton(buttonLastPressed);
enableButton(buttonPressed);
buttonLastPressed = buttonPressed.getIndex()
}
}
Saves you from looping through each and every button to disable it.
Define id of button 1 to 100
When press button occurs save it's id in some member variable like previous_pressed
Before updating a previous_pressed value find and unpress previous pressed button like this
Button previous_pressed_button = (Button) findViewById(previous_pressed);
Now you have the previous pressed button, So upress it or whatever.

How to check if a button is clicked or not?

I have a Activity in android that has 4 buttons.
The first 3 buttons fetches a json data from a weather API for 1 day, next 5 days and next 10 days respectively.
I have a 4th button placed at the bottom of the screen, which takes user to second activity.
I want to restrict the entry of user to second Activity if no button from top 3 is clicked.
If the data is fetched, I mean any one of the top 3 buttons have been clicked, allow him to go to second activity on 4th button click else show a message.
How can i check on click of 4th button if any of the top 3 buttons have been clicked before?
Thanks
Put a boolean field in your activity, name it clicked and set it to false on the onCreate method of your first activity, then in the onClick method of your 3 buttons, set it to true,
and in the onClick method of your 4th button check it, if it's true go startActivity, else launch a Toast
You can make the 4th button look disable in "OnCreate" with the function "setEnabled"(may be wrong),
and then just set "setOnClickListener" for the 4th button when you click any of the others.
ps.
Can provide code example if needed.
Why don't you use if statement? You can keep the clicked count data under the first three buttons. Like this;
import java.util.stream.*;
int[] btnMemory = new int[4];
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnMemory[0] = 1;
// your code
}
});
after, you can check it with if statement under 4th button;
button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int sum = IntStream.of(btnMemory).sum();
if(sum >= 3)
// your code
}
});

Categories

Resources