I'm having a small problem trying to get the checked values from a radio group.
I've used a for loop to create my questions and radiogroups.
LinearLayout a = (LinearLayout) findViewById(R.id.aLayout);
for (int k = 1; k < 11; k++){
//CREATE QUESTIONS
TextView q = new TextView(this);
q.setText(k + ")" + " " + pssQ[k]);
a.addView(q);
//CREATE RADIO BUTTONS
final RadioButton[] rB = new RadioButton[5];
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(LinearLayout.VERTICAL);
for(int i = 0; i < 5; i++){
rB[i] = new RadioButton(this);
rg.addView(rB[i]);
rB[i].setText(a1[i]);
}
a.addView(rg);
//get values here??
}
The code works how I intended it to.
The problem is that I don't know how to get the checked radio-button from each iteration. There is ten in total that I want to collect.
Any guidance would be appreciated. And if there's an easier alternative I'd be open to suggestions.
Thanks in advance. :)
You need to attach a check change listener to each of your RadioGroup within the loop:
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// your logic here
}
});
A way will be to use an additional variable (for example) isChecked as a boolean variable ,so when isChecked is true you will can spot which radio button is checked by the user on any iteration.
Related
I have one button in place. For each number a user sets in a text field, the appropriate number of buttons adds to the ui. But for every change of number i want all the buttonAdded to be removed, but not the first one, that is already in place. How do i do that? It didn't work when i tried it like in the exmaple:
final int number = Integer.parseInt(this.textField.getValue());
if(number > 1) {
for(int i = 1; i < number; i++) {
final XdevButton buttonAdded = new XdevButton("Button " + i);
this.verticalLayout.removeComponent(buttonAdded);
this.verticalLayout.addComponent(buttonAdded);
}
}
Is there a way to create new buttons with a defined component name in my loop?
Something like this:XdevButton button + i = new XdevButton()?
Edit:(Tried it with a list) - doesn't work.
private void textField_valueChange(final Property.ValueChangeEvent event) {
final int number = Integer.parseInt(this.textField.getValue());
final List<XdevButton> addedButtons = new LinkedList<>();
for(final XdevButton btn : addedButtons) {
this.verticalLayout.removeComponent(btn);
}
addedButtons.clear();
if(number > 1) {
for(int i = 1; i < number; i++) {
final XdevButton buttonAdded = new XdevButton("Button " + i);
addedButtons.add(buttonAdded);
for(final XdevButton btn : addedButtons) {
this.verticalLayout.addComponent(btn);
}
}
}
}
What am i missing?
That indeed won't work, nor is it possible to name a button the way you are asking.
You have a few options, if you don't want to reuse the old buttons.
If the vertical layout only contains buttons, or if you know how many components there are before the buttons, you can remove them by index:
for(int i = 1; i < number; i++) {
this.verticalLayout.getElement().removeChild(i);
}
You can also create a list or other collection to keep track of the buttons, this way you can reuse them as well:
private List<Button> buttons = new LinkedList<>();
...
// Not enough buttons, need to add new ones
if (number > buttons.size()) {
for(int i = buttons.size(); i < number; i++) {
Button buttonAdded = new Button("Button " + i);
buttons.add(buttonAdded);
}
}
// Too many buttons, remove the extras
else if (buttons.size() > number) {
List<Button> buttonsToRemove = buttons.subList(number, buttons.size());
buttonsToRemove.forEach(verticalLayout::remove);
buttonsToRemove.clear();
}
I would create a separate layout holder for buttons to be removed/added and work with it. For testing purposes I've replaced your XdevButton with a general Vaadin Button class. This seems to work according to your specs:
#Route("customView")
public class CustomView extends VerticalLayout {
VerticalLayout buttonHolder=new VerticalLayout();
public CustomView (){
TextField tf=new TextField("Enter amount of buttons");
tf.addValueChangeListener(event->{
final int number = Integer.parseInt(event.getValue());
if(number > 1) {
buttonHolder.removeAll();
for(int i = 0; i < number; i++) {
final Button buttonAdded = new Button("Button " + i);
buttonHolder.add(buttonAdded);
}
}
});
Button alwaysInPlace=new Button("This button is never removed");
add(alwaysInPlace);
add(buttonHolder);
}
}
Example is created in V14, but should be similar in all other versions
I have radio button in radiogroup, which is if i click it i'll get the value and show it as a Toast Message, and then i want to store the value into Array.
Here is my code.
This code has function to get value to text of radiobutton.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton checkedRadioButton = (RadioButton) view.findViewById(i);
String text = checkedRadioButton.getText().toString();
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
}
});
After i get the value in Array, i want to sum the data in new variable.
Declare a list outside of the setOnCheckedChangeListener and every time you click the radio button add that element to the list:
ArrayList mArrayList = new ArrayList();
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
RadioButton checkedRadioButton = (RadioButton) view.findViewById(i);
String text = checkedRadioButton.getText().toString();
mArrayList.add(Integer.parseInt(text));
Toast.makeText(getContext(), text, Toast.LENGTH_SHORT).show();
}
});
And than when you want to get the sum of the list:
If you are using java 8:
int sum = mArrayList .stream().mapToInt(Integer::intValue).sum();
if not:
int sum = 0;
for(Integer iterator: mArrayList){
sum+=iterator
}
//after that your sum is ready
That's all
Edit
Just make sure that all radio buttons are Numbers. If you face empty number or a character your Android app will crash giving a NumberFormatException
To store the values in an array, use ArrayList
ArrayList<Integer> myList = new ArrayList<Integer>();
Every time you want to store an int value, use:
myList.add(the int value);
In your case, substitute the int value with Integer.parseInt(text)
For the summing process: iterate the array with a simple for as follows
int total = 0;
for (int i=0; i<myList.size(); i++){
total += myList.get(i);
}
I'm working on a multiple choice quiz application, and what I'm trying to accomplish is having my "Next Question" button get values from an array in which my questions/answers are stored. The code I have so far loops through the first question, [0][0] etc. as well as the second question stored at [1][0] etc. I have 10 questions stored in my array, and I'm trying to loop through all of them. What should I change in this code to make that happen?
public void addListenerOnButton(){
Button nextQButton = (Button) findViewById(R.id.nextQButton);
nextQButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 0; i < qAndA.length; i++) {
TextView questionText = (TextView) findViewById(R.id.questionText);
questionText.setText(qAndA[i][0]);
RadioButton radioButton1 = (RadioButton) findViewById(R.id.radioButton1);
radioButton1.setText(qAndA[i][1]);
RadioButton radioButton2 = (RadioButton) findViewById(R.id.radioButton2);
radioButton2.setText(qAndA[i][2]);
RadioButton radioButton3 = (RadioButton) findViewById(R.id.radioButton3);
radioButton3.setText(qAndA[i][3]);
RadioButton radioButton4 = (RadioButton) findViewById(R.id.radioButton4);
radioButton4.setText(qAndA[i][4]);
}
}
});
}
I see no need for a for loop here. Why not just have a counter which increments every time the button is clicked?
int count = 0;
Your onClick method could look something like this.
questionText.setText(qAndA[i][count]);
count++;
In my activity, I am creating a dynamic radiogroup. I have some questions and answers in Sqlite database, retrieving them in activity and then set in RadioGroup. This is working fine. But after that, I want to get all ID of selected radio button by user to store them in database. In general, we do something like this when we have option's ID :
id1=rdgroup1.getCheckedRadioButtonId();
que1=(RadioButton)findViewById(id1);
ans1=que1.getId()+""; // so here I will get radio button's ID.
So my questions is, how will I get selected radio button's ID. Here's my code for dynamically creating radiogroup.
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1=db.rawQuery("SELECT * FROM QueTable WHERE AgeGroup='10-20'", null);
c1.moveToFirst();
int i = c1.getCount();
if(i > 0)
{
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);
title.setText(questions);
title.setTextColor(Color.BLACK);
mLinearLayout.addView(title);
// create radio button
answers=c1.getString(2);
String[] answer = answers.split(",");
rb = new RadioButton[5];
rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
int k = answer.length;
for (int j = 0; j < k; j++)
{
rb[j] = new RadioButton(this);
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
mLinearLayout.addView(rg);
c1.moveToNext();
i--;
}
}
The place where you create RadioButton set and Id to it
for (int j = 0; j < k; j++)
{
RadioButton rb = new RadioButton(this);
rb.setId(Somenumber + j)
rb[j] = rb;
rg.addView(rb[j]);
rb[j].setText(answer[j]);
}
Like this you can setId or also if you want you can add tag to process.
rb.setTag(SomeObject)
You need to set an ID for your programmatically created RadioButton in order to find it using findViewById as you show in your first code.
To set the ID for your RadioButton, you can use View.setId(). The documentation says:
Sets the identifier for this view. The identifier does not have to be
unique in this view's hierarchy. The identifier should be a positive
number.
The identifier does not have to be unique, but if it's not unique, findViewById will return the first occurence, so you can use the static method View.generateViewId added on API level 17.
If you are using lower APIs, you may want to write your own function to find a suitable (unused) ID. You can take a look at Android: View.setID(int id) programmatically - how to avoid ID conflicts?
Ok..So finally I got the solution. I am going to share complete code here that will create dynamically radiogroup and radiobuttons from database. Here is code below :
private static final int RB_ID = 100;
int k=0,len=0,r=0,p = 0,q=0, len = 0;
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
c1 = db.rawQuery("SELECT * FROM QueMotion WHERE AgeGroup ='"+Age+"' LIMIT 5", null);
c1.moveToFirst();
int i = c1.getCount();
rg = new RadioGroup[i];
rb = new RadioButton[i*5];
if (i > 0) {
Log.w("START", "start");
while (i > 0)
{
TextView title = new TextView(this);
questions = c1.getString(1);// retrive from database
title.setText(questions);
title.setTextColor(Color.BLACK);
title.setTypeface(null, Typeface.BOLD);
title.setPadding(0, 0, 0, 10);
mLinearLayout.addView(title);
answers = c1.getString(2);// retrive from database
String[] answer = answers.split(",");// will create options for radio button.
rg[p] = new RadioGroup(this);
rg[p].setOrientation(RadioGroup.VERTICAL);
len=len+answer.length;
for (int j = 0; j < answer.length; j++)
{
rb[q] = new RadioButton(this);
rg[p].addView(rb[q]);
rb[q].setId(k + RB_ID);
rb[q].setText(answer[j]);
k++;
q++;
}
mLinearLayout.addView(rg[p]);
c1.moveToNext();
i--;
p++;
}
//Submit button click
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (rg[0].getCheckedRadioButtonId() == -1)
{
Log.e("Nothing selected", "Nothing selected");
}
else
{
for (r = 0; r < len; r++) {
if (rb[r].isChecked()) {
RadioButton id = (RadioButton) findViewById(rb[r].getId());
String radioText = id.getText().toString();
c3.moveToFirst();
Log.e("RadioString", radioText);
} else {
Log.e("RadioString", "nothing");
}
}
}
}
});
question with either easy or impossible answer, dunno. I'm new and I want to create new TextView's within a loop, but I'm having problem with TextView's variable name. I need it to be unique.. Thanks.
int i = 1;
while (i<=10) {
String asd = String.valueOf(i);
TextView textView+asd = new TextView(this);
//new textView+asd.setText("asdd");
i++;
}
You can't do it like you posted. You need to create array of TextView's. TextView textViews[] = new TextView[10]; for(int i=0; i<textViews.length; i++) { textViews[i] = new TextView(this); }
You will need to use your layout and do something like this
final int x = 5; // # of TextViews you want
int i = 0;
final TextView[] textViews = new TextView[x];
while (i < x) {
TextView newTextView = new TextView(this); // this needs to be the proper context
newTextView.setText("Whatever");
layout.addView(newTextView); // Need to bring in your layout before this
textViews[i] = newTextView;
i++;
}