setOnCheckedChangeListener is never called - android

I am trying all day to understand, why my method setOnChangeListener is never called...it works well until the first Toast...The second toast never appear. What is wrong? Should i pass someway the view to the onCheckedChangeListener? I have activity, where user can click on button, then he get alertdialog, with 3 radio buttons and radiogroup inside. I want to get, what radiobutton he has choosen. No matter what i tried. Nothing worked. I get always only the one radio button as checked, which i checked in xml layout...Help...
Button setWeekType = (Button) findViewById(R.id.setWeekType);
if (setWeekType != null) {
setWeekType.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new AlertDialog.Builder(report_activity.this, R.style.DialogTheme)
.setView(R.layout.dialog_type_day)
.setCancelable(true)
.setPositiveButton("Choose", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
final View child = getLayoutInflater().inflate(R.layout.dialog_type_day, null);
final RadioGroup radiogroup = (RadioGroup)child.findViewById(R.id.radiogroup);
final RadioButton bhome = (RadioButton)child.findViewById(R.id.bhome);
final RadioButton bwork = (RadioButton)child.findViewById(R.id.bwork);
final RadioButton bschool = (RadioButton)child.findViewById(R.id.bschool);
bwork.setChecked(true);
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
Toast.makeText(getApplicationContext(), "1", Toast.LENGTH_SHORT).show();
if (checkedId == bhome.getId()) {
bhome.setChecked(true);
}if (checkedId == bwork.getId()) {
bwork.setChecked(true);
}if (checkedId == bschool.getId()) {
bschool.setChecked(true);
}
}
});
}
})
.setNegativeButton("Cancel", null)
.show();
}
});
}

I run your code and I think the problem is with child View, It's null! So radiogroup is null too and the listener will never be set, Use logging to see yourself.
I recommend you to create a custom DialogFragment to get rid of nested inner classes and manage things much more easier.
In case you need a tutorial:
http://www.androidbegin.com/tutorial/android-dialogfragment-tutorial/

You can make that to else if. Example :
if (checkedId == bhome.getId()) {
bhome.setChecked(true);
}else if (checkedId == bwork.getId()) {
bwork.setChecked(true);
}else if (checkedId == bschool.getId()) {
bschool.setChecked(true);
}
And you can make oncheckedchangelistener in a top of on click listener

You are calling setOnCheckedChangeListener from within the (positive) button callback. This means that your second Toast can only be shown after the user has already clicked the "Choose" button (which presumably, is too late).
You need to get the find the radio group from the AlertDialog instance and call setOnCheckedChangeListener before you show the dialog.

Related

how to validate fragment RadioGroup inside from MainActivity Button click?

I have a Fragment with Dynamic Radio group. When User Select any radio button. I am Passing value instead of radio button and load another thing with next button click from MainActivity. But If User not selected any radiobutton, MainActivity "NextButton" need to check Validation like Radiogroup to radiobutton ischeck() or not, If not Then need to show Toast.
Sorry for my Bad English.
Radio Grounp Code in Fragment:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton= group.findViewById(checkedId);
answer = radioButton.getText().toString();
// Toast.makeText(getActivity(), ""+answer, Toast.LENGTH_SHORT).show();
answerModel = new AnswerModel(id, question, answer);
Double referId = (Double) questionDataModel.getOptions().get(checkedId - 1).getReferTo();
nextId = referId.intValue();
// Toast.makeText(getActivity(), ""+referId, Toast.LENGTH_SHORT).show();
// Toast.makeText(getActivity(), ""+answerModel.getId()+"\n"+answerModel.getAnswer()+"\n"+answerModel.getQuestion(), Toast.LENGTH_SHORT).show();
sendDataInterface.sendata(nextId, answerModel);
}
});
Data Receive from MainActivity with NextButton:
I need to check Validation within this method actually
#Override
public void sendata(int data, AnswerModel answerModel) {
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
goToNextQuestion(data);
// Toast.makeText(MainActivity.this, ""+data, Toast.LENGTH_SHORT).show();
}
});

ListView with CHOICE_MODE_SINGLE. Select up to one choice

I have a multi choice list inside an AlertDialog.
Reading the documentation of CHOICE_MODE_SINGLE, I thought that you could have one or no item checked but for me it behaves like a Radio Button List. It starts with all checkboxes unchecked by default by once I check one, it cannot be unchecked.
I tried hacking it with manual setItemChecked inside onClick but that is not a solution.
What am I doing wrong? How to achieve one or no checkbox in a ListView?
Here's my code:
builder.setMultiChoiceItems(titles, new boolean[titles.length], new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int position, boolean b) {
if (selectedId == -1) {
selectedId = position;
} else {
if (selectedId == position) {
mDialog.getListView().setItemChecked(position, false);
selectedId = -1;
} else {
mDialog.getListView().setItemChecked(selectedId, false);
selectedId = position;
}
}
}
});
mDialog = builder.create();
mDialog.getListView().setChoiceMode(AbsListView.CHOICE_MODE_SINGLE);
your code isn't working because the method that you are using, setItemChecked, doesn't change the selected state when receive a false and is working on CHOICE_MODE_SINGLE, which is the normal behaviour of a group of radio buttons. You can see it by yourself with "Go To Implementation" in Android Studio (Ctrl + RightClick over the method).
Also, it's not recommended to use checkboxes for a single choice selector as it will confuse your users. You can easily get radio buttons replacing setMultipleChoiceItems by setSingleChoiceItems. It also apply the single choice mode to your ListView, so you can get rid of your last line.
To allow the user to perform an empty selection with radio buttons you have mainly 2 options:
Add an extra items to your list representing the empty selection option. Label it as "None", "Uncheck" or something similar
Add an extra button to your dialog to dismiss the dialog and return an empty selection.
Here you have a sample of implementation of the first option adding dynamically the empty item for a better re-usability ;)
Screenshot
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String title = "Select your favourite language";
String[] items = {"English", "Spanish", "Chinese", "Java"};
String emptyItemTitle = "NONE OF THEM";
int initialSelection = 0;
showSingleChoiceDialogWithNoneOption(title, items, initialSelection, emptyItemTitle);
}
private void showSingleChoiceDialogWithNoneOption(String title, final String[] titleItems, int initialSelection, String emptyItemTitle ) {
final String[] extendedItems = addEmptyItem(titleItems, emptyItemTitle);
final int[] selectedPosition = {initialSelection};
new AlertDialog.Builder(this)
.setTitle(title)
.setSingleChoiceItems(extendedItems, initialSelection, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
selectedPosition[0] = which;
Log.d("MyTag", String.format("Selected item '%s' at position %s.", extendedItems[which], which));
}
})
.setNegativeButton("Cancel", null)
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("MyTag", String.format("Confirmed the selection of '%s' at position %s.", extendedItems[selectedPosition[0]], selectedPosition[0]));
onSelectionConfirmed(selectedPosition[0]);
}
})
.show();
}
#NonNull
private String[] addEmptyItem(String[] titleItems, String emptyTitle) {
String[] tempArray = new String[titleItems.length + 1];
tempArray[0] = emptyTitle;
System.arraycopy(titleItems, 0, tempArray, 1, titleItems.length);
return tempArray;
}
private void onSelectionConfirmed(int position) {
if (position==0){
//Handle your empty selection
}else{
//Selected item at position
}
}
}

Android RadioGroup OnCheckedChangeListener

I have an Activity which implements both Checkbox.OnCheckedChangeListener and RadioGroup.OnCheckedChangeListener The groups are both dynamically generated and passed the same Activity as the listener.
However, when I click on a RadioGroup, the RadioGroup.OnCheckChangeListener is completely ignored but here's where it gets weird. It triggers CheckBox.OnCheckChangeListener! I tried casting the activity to the RadioGroup listener before passing it, but RadioGroup cannot even accept it, only the CheckBox listener gets through.
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_MULTI_ANSWER")) {
String selected = buttonView.getText().toString();
if (subquestion.getAnswer().getDataList() != null) {
Answer answer = subquestion.getAnswer();
ArrayList<String> checked = answer.getDataList();
if (checked.contains(selected)) {
checked.remove(selected);
Log.d("Checkbox" + buttonView.getId(), "unchecked");
} else {
checked.add(selected);
Log.d("Checkbox" + buttonView.getId(), "checked");
}
} else {
ArrayList<String> checked = new ArrayList<String>();
checked.add(selected);
subquestion.getAnswer().setDataList(checked);
Log.d("Checkbox" + buttonView.getId(), "checked");
}
}
if(subquestion.getQuestionType().equals("MULTIPLE_CHOICE_SINGLE_ANSWER")) {
RadioGroup group = buttonView; //CAN'T BE DONE
String selected = group.getFocusedChild().getId() + "";
subquestion.getAnswer().setData(selected);
Log.d("Radiobutton " + selected + group.getFocusedChild().getId(), "selected");
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
//This does NOTHING, can't even be passed to the RadioGroup as a listener
}
How do I get the RadioGroup from the buttonView? I generate everything in code and it's different every time so there are no static id's to determine what's clicked. I pass an id to the radiobuttons to let me know which is which but I can't get to it like this.
It works perfectly for the checkboxes, it's just that Android seems to throw the wrong event and uses the wrong event handler for RadioGroup.
Thank you for reading!
Call this method for RadioGroup.OnCheckChangeListener and pass RadioGroup as argument
public void onRadioChangeListener(RadioGroup radioGroup){
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// write your code here
}
});
}

How to give radio button functions in a alert dialog?

So I have made a alert dialog box with 3 options. So, if the first option is selected and something specific is entered into a edit text field it changes a text view into something specific. How do I go about giving the radio button a function?
Check this
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup);
radioGroup.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int checkedRadioButton = radioGroup.getCheckedRadioButtonId();
switch (checkedRadioButton) {
case R.id.firstRadioBtn: //id of first radio button
//code goes here if first radio button is clicked
break;
case R.id.secondRadioBtn://id of second radio button
//code goes here if second radio button is clicked
break;
case R.id.thirdRadioBtn://id of third radio button
//code goes here if third radio button is clicked
break;
}
}
});
Hope it helps.
I think this is what you want....
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
// your code here
}
});
here inside the code block you will do something specific or whatever.... ;)
you must use
RadioGroup radioGroup = (RadioGroup) dialog.findViewById(R.id.yourRadioGroup);
if this is a part of your dialog....
Hope this helps
you can get it in a much easier way like this
builder.setSingleChoiceItems(items, checkeditem, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});

Radio Button in Radio Group does not show checked after clicking on it

I am having a problem with a radio button that is in a radio group.
I have an app that is a quiz application and I ask 5 questions.
When run the application in my Android emulator all the questions have no problem but only on the 3rd question. When I click with my mouse on the radio button it seems toggle to a checked state but then it unchecks right away. Has anyone seen this kind of behavior?!
I setup this Radio group and dynamically add 4 radio buttons in a radio group and then use an OnCheckedChangeListener() event to capture the change.
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
for(int i=0; i<=3;i++)
{
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
if (btn.isPressed() && questNo < 6)
{
if (corrAns[questNo-1].equals(btn.getText()) && flag==true)
{
Log.e(LOG_TAG,"onCheckedChanged: correct answer = btn Text");
score++;
flag = false;
checked = true;
}
else if(checked==true)
{
Log.e(LOG_TAG,"onCheckedChanged: correct answer != btn Text");
score--;
flag = true;
checked=false;
}
}
}
Log.e(LOG_TAG, "Score:"+ Integer.toString(score));
}
});
I have noticed that it happens randomly on different questions and only on first radiobutton that is selected but if you select another one after then the functionality returns to normal. Any ideas?
I had the same bug. I'm also using dynamic radioGroups and buttons. This is working for me:
private OnCheckedChangeListener rblLikert_Listener = new OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
int selectedIndex = group.getCheckedRadioButtonId();
if(selectedIndex != -1)
{
m_likertValue = radioButtonValue;
int buttonId = group.getCheckedRadioButtonId();
Logger.i("button id: " + String.valueOf(buttonId));
RadioButton selectedButton = (RadioButton)findViewById(buttonId);
selectedButton.toggle();
Logger.i(" is checked: " + String.valueOf(selectedButton.isChecked()));
}
}
};

Categories

Resources