How to get checked radio button's id created dynamically in android - java

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");
}
}
}
}
});

Related

Removing added buttons Vaadin

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

Creating a string using onClick and getting the final value to search to the array

I'm new to android and I am currently having this problem on onClick():
I have dynamically created textViews within a TableLayout() and each textviews have onClickListener. The code is like this:
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
I also initialized a method called checkAns() and it goes like this:
private boolean checkAns(TextView uTxt, List<String> list) {
String word = uTxt.getText().toString().toLowerCase();
if (list.contains(word)) {
return true;
}
else {
return false;
}
}
The purpose of that method is to catch the created word and check if the formed word is on the array.
But that method always returns false. Is there anything wrong with my logic?
Any help, comments, and suggestions are welcome. :)
EDIT:
#k3b ask me where the list is populated. So here is the full code of the textView grid that i created:
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TableLayout table = (TableLayout) findViewById(R.id.mainLayout);
table.setTag(1);
final Typeface font = Typeface.createFromAsset(getAssets(), "kg.ttf");
final Typeface font2 = Typeface.createFromAsset(getAssets(), "futura.ttf");
final String[] wordArray = new String[Category.size];
final TextView uTxt = (TextView)findViewById(R.id.userTxt);
for(int i = 0; i < Category.size; i++){
wordArray[i] = listahan[i];
}
final List<String> list = Arrays.asList(wordArray);
for (int i = 0; i < input.length; i++) {
final LinearLayout rowLayout = new LinearLayout(this);
rowLayout.setOrientation(LinearLayout.HORIZONTAL);
rowLayout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
final TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
row.setGravity(Gravity.CENTER_HORIZONTAL);
row.setTag(i);
int k = 0;
for (int j = 0; j < input.length; j++) {
final TextView text = new TextView(this);
Character temp = input[i][j];
text.setText(temp.toString());
text.setPadding(20, 20, 20, 20);
text.setTag(i + " " + j);
text.setTextSize(txtSize);
text.setTypeface(font);
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//change the color of tapped textview
text.setTextColor(Color.WHITE);
text.setBackgroundColor(Color.parseColor("#c04485ed"));
String a = view.getTag().toString();
String b = text.getText().toString();
uTxt.setText(""+uTxt.getText().toString() + b);
if(uTxt.length() == 4){
if(checkAns(uTxt, list)){
Log.e("OUTPUT: " , uTxt.getText().toString().toLowerCase() + " IS ON THE ARRAY!");
}
else if (!checkAns(uTxt, list))
{
Log.e("OUTPUT: " , uTxt.getText().toString() + " IS NOT ON THE ARRAY!");
}
}
}
});
text.setGravity(Gravity.CENTER);
row.addView(text);
}
Thanks for all the help guys. I managed to fix the error. It seems that the code that initialized my array of words is not properly coded! Thanks guys!

Getting checked radio buttons values

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.

Remove all Rows Programmatically from TableLayout

i use following code to remove rows out off my tablelayout;
System.out.println(vi); gives me 4 unique rows and thats right but why my loop is not removing all rows at once. I need to click 3 times.
This code is placed in myOnclickHandler;
public void onClick(View v) {
TableLayout container = (TableLayout) v.getParent().getParent();
int childcount = container.getChildCount();
View vi;
for (int i = 0; i < childcount; i++) {
vi = container.getChildAt(i);
container.removeView(vi);
System.out.println(vi);
}
}
try it :
row = (TableRow)findViewById(R.id.row);
table.removeView(row);
use this it keep only header row.
if (table.getRootView() != null) {
int i = 1;
while (table.getChildCount() != 1) {
table.removeViewAt(i);
}
}

TextView variable name + string combining

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++;
}

Categories

Resources