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
}
Related
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();
}
}
});
}
I want to highlight right and wrong option when user clicks a button after checking an radio button. If that option is right, highlight. Else highlight right option.
Is there any way to get radio button id in a group based on its value? Or Do I need to use switch case?
I searched enough but not able to find out what I need.
Edit
I have simple layout which contains one question, 4 choices, one button. User check a radio button and click the check button. If user selects wrong option, highlight the correct option. I know what is correct option by value.
choice1, choice2, choice3, choice4 are four radio buttons. User checks choice3. But choice2 is correct. How do I select choice2 by value in this radio group.
group.getRadioButtonId("choice2")
Anything similar to this?
You could iterate through the children of your RadioGroup to get the required one:
int count = radioGroup.getChildCount();
for (int i = 0 ; i < count; i++) {
RadioButton button = (RadioButton) radioGroup.getChildAt(i);
if (button.getText().equals("choice2")) {
int id = button.getId(); // the ID you're looking for
}
}
You Can check like this
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
int rbId = group.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
switch (group.getId()) {
case R.id.radiogroupID:
if (rb.getText().toString().equalsIgnoreCase("right")) {
// your logic
} else {
//your logic
}
}
}
you can use these line. its working for me
int checkedId = radioGroup.getCheckedRadioButtonId();
View radioButton = radioGroup.findViewById(checkedId);
int radioId = radioGroup.indexOfChild(radioButton);
RadioButton btn = (RadioButton) radioGroup.getChildAt(radioId);
First check which option is true. hear choice 2 OK. set by default is checked true and than check user checked value . if user select other option than display message and pass true option we already checked true
Create an int array with all the ids of the radiobutton
int[] rb_IDs=new int[]{R.id.rb1,R.id.rb2,R.id.rb3};
Then inside your button click :
RadioGroup rg=(RadioGroup) findViewById(R.id.rg);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i=0;i<rb_IDs.length;i++)
{
RadioButton rb=(RadioButton)findViewById(rb_IDs[i]);
if (rb.getText().toString().equals("YOUR CORRECT ANSWER")&&!rb.isChecked())
{
//
//Do your thing
//
//ID of the correct answer Radiobutton is
int id=rb_IDs[i];
//HighLighting the answer
rb.setBackgroundColor(Color.parseColor("#00ff00"));
break;
}
}
}
});
Two buttons getting selected in the radio group.
I do not know where I am getting wrong. Please help me out.
final RadioGroup rg=new RadioGroup(Survay_MainActivity.this);
rg.clearCheck();
rg.setId(Integer.valueOf(entry1.getKey()));
Log.v("rg getid", "rg"+rg.getId());
for(int i =0;i<values.size();i++){
// Create Button
final RadioButton btn = new RadioButton(Survay_MainActivity.this);
btn.setId(i);
btn.setTextColor(Color.parseColor("#000000"));
btn.setBackgroundColor(Color.TRANSPARENT);
btn.setGravity(Gravity.LEFT);
btn.setText(values.get(i));
rg.addView(btn);
btn.setLayoutParams(params);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
JSONObject quesAns = new JSONObject();
String ans=btn.getText().toString().trim();
try {
quesAns.put(String.valueOf(rg.getId()), ans);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonarray.put(quesAns);
Log.v("jsonarray", "jsonarray"+jsonarray);
}
});
}
views.addView(rg);
1) I am creating the RadioGroup out of the loop.
2) Adding radio button to the RadioGroup in the for loop
3) When the loop finishes the RadioGroup is added to the linerlayout.
You just need to change different ids for different radio button.
There may be some id clash in gen file.
Radio button1 : android:id="#+id/one
Radio button2 : android:id="#+id/two"
Radio button3 : android:id="#+id/three"
Hope this would help.
There are some things misplaced these changes you have to make out.
1.Change your OnClickListener by OnCheckChangeListener
2.Clear check your radioGroup after adding all radioButtons and before adding it in LinearLayout.
Your problem comes from the fact that you are setting an id for your items manually
rg.setId(Integer.valueOf(entry1.getKey()));
btn.setId(i);
Android works with id's generated automatically that are different. Setting the id's manually it might happen that you give the same ID to the radio group and the radio button.
I used your code and set the group to ID 3 and radios from 0 to 4.
Needless to say that after I click the button with id 3 it always stays on because the group has the same id.
So, try to remove the id setting part, or, if you insist make sure you always have distinct id's.
I faced the same problem. The cause is the RadioGroup's id is same as one of RadioButtons
the problem is this line. you didn't send where is this code belonged to. when you get out of this scope and come back you will create new RadioGroup. You should have one and only one RadioGroup so the RadioButtons have same RadioGroup and by default one of them will be selected. To this, you can define RadioGroup in an XML and use this to define variable for it RadioGroup rg = (RadioGroup) findViewById(R.id.YOURNAME); or you can define your RadioGroup as Instance variable(Global).
final RadioGroup rg=new RadioGroup(Survay_MainActivity.this);
I have 4*7 table and I want to handle every Edit text there , when the user clicks on the 5th edit text for long enough so that the menu pops up he can choose what color he wants.
the problem is how should I do this, I have 4*7 edittexts so I should call registerForContextMenu(View) 28 times even if I did this How can I handle it in onContextItemSelected(menuItem) ?
I don't want to put the whole fragment's view since everytime the user clicks for too long on any position the menu will pop up , so I don't want that.
Edit:
I tried this in the onCreateContextMenu:
if(v.getId() == R.id.table_item1){
Position = 1;
}
and check for the position in the onContextItemSelected , is there a better way/ faster way than this ? since I'll need to put 28 if there :(
You could name your EditTexts edit1, edit2, edit3 etc.
Then you could do a loop
for(int i=1; i<=28; ++i) {
int resId = getResources.getIdentifier("edit" + i, "id", getPackageName());
EditText edt = (EditText)findViewById(resId);
edt.registerForContextMenu(...)
}
and the same in other places where you have to iterate over your EditTexts
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.