How to get the id of a radio button in Java? - java

I've created pragmatically 5 radio groups with 4 radio buttons each. How can i get the Id of the radio buttons? Very important, i dont't want to use setOnCheckedChangeListener. Here is my code.
radioGroup = new RadioGroup[5];
answer = new RadioButton[4];
int i = 0;
for (Question qn : questions) {
radioGroup[i] = new RadioGroup(this);
radioGroup[i].setId(i);
int j = 0;
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
answer[j].setText(an.getAnswer());
answer[j].setId(j);
radioGroup[i].addView(answer[j]);
j++;
}
}
linearLayout.addView(radioGroup[i]);
answer[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int checkedRadioButtonId = v.getId();
RadioButton checkedRadioButton = (RadioButton) findViewById(checkedRadioButtonId);
if (checkedRadioButton.isChecked()) {
Toast.makeText(getApplicationContext(), "Checkbox" + checkedRadioButtonId + " checked", Toast.LENGTH_SHORT).show();
}
}
});
i++;
}
Thanks!

as in log :
ArrayIndexOutOfBoundsException: length=4; index=4
Because answer Array is size of j instead of i, so move RadioButton click listener inside for loop:
for (Answer an : answers) {
if (qn.getID() == an.getQuestion_id_answer()) {
answer[j] = new RadioButton(this);
...your code here...
answer[j].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// your code here...
}
});
j++;
}
}

Related

background color and font Family in editext should change when buttons are been clicked

I am trying to create an activity which contain an edittext, of which background color and fonts should be changed whenever the button is been clicked.
To perform these actions on the edittext, I have created two ArrayList of int value and saved all the color's id and the font's id in this ArrayList. whenever the button is clicked the background color didn't change but the color's Hexa code print in the edittext and these color codes comes with extra ff values in front of every color's code like #ff1EFA9D and in the font method I am getting an error that says:-
Unable to start activity ComponentInfo{com.nanb.alpha/com.nanb.alpha.postcreater}: java.lang.ArrayIndexOutOfBoundsException: length=4; index=-1
I have tried to find the solution over the internet but didn't get any solution that satisfies the error.
code For changing the background color and font of the edittext is given below
private EditText editText;
private ImageButton color,font;
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(10);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(6);
int fontstylename=R.font.abril_fatface,bgcolor=R.color.white,fontpostion = fontstyle.indexOf(fontstylename);
int postion = bgcolorlist.indexOf(bgcolor);
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolor);
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
int newpostion = postion + 1;
editText.setText(bgcolorlist.get(newpostion));
postion = newpostion;
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontpostion));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
int newpostion = fontpostion + 1;
editText.setText(fontstyle.get(newpostion));
fontpostion = newpostion;
}
}
});
}
Help me to solve these errors.
Try changing your codes to this:
ArrayList<Integer> bgcolorlist = new ArrayList<Integer>(11);
ArrayList<Integer> fontstyle = new ArrayList<Integer>(7);
int fontpostion = 0;
int postion = 0;
private void Initialization() {
cancel = view.findViewById(R.id.backbutton);
createnextbutton = view.findViewById(R.id.nextbutton);
editText = view.findViewById(R.id.textpost);
color = view.findViewById(R.id.bgcolorbutton);
font = view.findViewById(R.id.fontstyle);
}
//codes are for the background color changing
private void backgroundcolormethod() {
bgcolorlist.add(R.color.white);
bgcolorlist.add(R.color.darkGreen);
bgcolorlist.add(R.color.colorPrimaryDark);
bgcolorlist.add(R.color.colorAccent);
bgcolorlist.add(R.color.colorPrimary);
bgcolorlist.add(R.color.orange);
bgcolorlist.add(R.color.edittextbg5);
bgcolorlist.add(R.color.edittextbg4);
bgcolorlist.add(R.color.edittextbg3);
bgcolorlist.add(R.color.edittextbg2);
bgcolorlist.add(R.color.edittextbg1);
editText.setBackgroundColor(bgcolorlist.get(0));
color.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(postion == 10){
//Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(bgcolorlist.get(postion));
postion = 0;
}else{
postion++;
editText.setText(bgcolorlist.get(postion));
}
}
});
}
//codes for changing the fonts
private void fontstylemethod() {
fontstyle.add(R.font.abril_fatface);
fontstyle.add(R.font.cedarville_cursive);
fontstyle.add(R.font.alfa_slab_one);
fontstyle.add(R.font.annie_use_your_telescope);
fontstyle.add(R.font.aclonica);
fontstyle.add(R.font.aguafina_script);
fontstyle.add(R.font.arizonia);
editText.setTypeface(Typeface.defaultFromStyle(fontstyle.get(0)));
font.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fontpostion == 6){
Toast.makeText(view.getContext(),"last element",Toast.LENGTH_SHORT).show();
editText.setText(fontstyle.get(postion));
fontpostion= 0;
}else{
fontpostion++;
editText.setText(fontstyle.get(fontpostion));
}
}
});
}

How to prevent second click on radio button if it was already clicked in Android?

I want to stop the second click on a RadioButton, when someone has already clicked on a RadioButton in a RadioGroup. If someone clicks 2 times, the user not able to change that selected click. I am trying to prevent that with a boolean but it doesn't work. Where am I wrong?
This is my code:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
rb = (RadioButton) findViewById(checkedId);
user_radio_answer = (String) rb.getText();
rb.setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
#Override
public void onClick(View v) {
if (isChecked) {
if (rb.isChecked() ) {
isChecked = false;
}
}
if (correct_answer1.equals(user_radio_answer)) {
rb.setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show();
rb.setBackgroundColor(Color.parseColor("#FF5733"));
answer1 = rb_answer1.getText().toString();
answer2 = rb_answer2.getText().toString();
answer3 = rb_answer3.getText().toString();
answer4 = rb_answer4.getText().toString();
if (answer1.equals(correct_answer1)) {
rb_answer1.setBackgroundColor(Color.GREEN);
}
if (answer2.equals(correct_answer1)) {
rb_answer2.setBackgroundColor(Color.GREEN);
}
if (answer3.equals(correct_answer1)) {
rb_answer3.setBackgroundColor(Color.GREEN);
}
if (answer4.equals(correct_answer1)) {
rb_answer4.setBackgroundColor(Color.GREEN);
}
}
new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx");
}
});
}
});
Just remember if they have answered the question, and remember the view (RadioButton) that spawned the first answer, and check that RadioButton again whenever a RadioButton is clicked. This assumes all RadioButtons in the RadioGroup have the same onClick method.
boolean answered = false;
RadioButton radioAnswer;
public void answer1(View view) {
if (!answered) {
radioAnswer = (RadioButton) view;
answered = true;
} else {
radioAnswer.setChecked(true);
}
}
You can add two methods and then call them when needed. You can add a condition, if the radiobutton is checked then disable the group and if it is not checked then set it to enabled. When you clear your radiogroup you can also set buttons enabled.
public void disableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(false);
}
}
public void enableRG() {
for(int i = 0; i < radioGroup.getChildCount(); i++){
((RadioButton)radioGroup.getChildAt(i)).setEnabled(true);
}
}
Maybe you can set a global boolean flag.
`private boolean alreadyChecked = false;
radioGroup.setOnCheckedChangeListener(new
RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// checkedId is the RadioButton selected
rb = (RadioButton) findViewById(checkedId);
user_radio_answer = (String) rb.getText();
if (!alreadyChecked) {
rb.setOnClickListener(new View.OnClickListener() {
private boolean isChecked = true;
#Override
public void onClick(View v) {
if (isChecked) {
if (rb.isChecked() ) {
isChecked = false;
}
}
if (correct_answer1.equals(user_radio_answer)) {
rb.setBackgroundColor(Color.GREEN);
// Toast.makeText(getApplicationContext(), "Correct ☺ : " + user_radio_answer, Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Incorrect Answer :( ..Correct Answer : " + correct_answer1, Toast.LENGTH_LONG).show();
rb.setBackgroundColor(Color.parseColor("#FF5733"));
answer1 = rb_answer1.getText().toString();
answer2 = rb_answer2.getText().toString();
answer3 = rb_answer3.getText().toString();
answer4 = rb_answer4.getText().toString();
if (answer1.equals(correct_answer1)) {
rb_answer1.setBackgroundColor(Color.GREEN);
}
if (answer2.equals(correct_answer1)) {
rb_answer2.setBackgroundColor(Color.GREEN);
}
if (answer3.equals(correct_answer1)) {
rb_answer3.setBackgroundColor(Color.GREEN);
}
if (answer4.equals(correct_answer1)) {
rb_answer4.setBackgroundColor(Color.GREEN);
}
}
new RadioHttpAsyncTask().execute("http:xxxxxx-xxxxxxxxxx-xxxxxxxx");
}
alreadyChecked = true;
});
}
}
});`
You can disable it after click to stop listening to click events
rb.setEnabled(false);
Edit:
Or you can remove click listener once it is already clicked
rb.setOnClickListener(null);

Android Development. RadioButton keeps unselecting

I am building a little quiz app and let's say on Question 1, I select option B, then submit and the quiz gives me the next question. However for question 2 if I try to select B, the RadioButton quickly unchecks itself and it is completely uncheckable, until I select another radio button and then try B again. The pattern is, whatever option I selected in the previous question, is uncheckable in the next question unless I click on a different radiobutton and then try again. I'm attaching my code. Any help please?
public class MainActivity extends AppCompatActivity {
QuestionBank allQuestions = new QuestionBank();
String pickedAnswer = "", correctAnswer = "";
final int numberOfQuestions = allQuestions.list.size();
int questionNumber = 0;
boolean noSelection = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nextQuestion();
}
private void nextQuestion() {
if (questionNumber <= numberOfQuestions - 1) {
TextView questionLabel = (TextView) findViewById(R.id.question_text_view);
String fullQuestion = allQuestions.list.get(questionNumber).questionSet.get("question").toString();
fullQuestion += "\n\na) " + allQuestions.list.get(questionNumber).questionSet.get("a");
fullQuestion += "\nb) " + allQuestions.list.get(questionNumber).questionSet.get("b");
fullQuestion += "\nc) " + allQuestions.list.get(questionNumber).questionSet.get("c");
fullQuestion += "\nd) " + allQuestions.list.get(questionNumber).questionSet.get("d");
correctAnswer = allQuestions.list.get(questionNumber).questionSet.get("answer").toString();
questionLabel.setText(fullQuestion);
questionNumber++;
} else {
restart();
}
}
public void getSelectedAnswer() {
RadioButton radio_1 = (RadioButton) findViewById(R.id.option1_button);
RadioButton radio_2 = (RadioButton) findViewById(R.id.option2_button);
RadioButton radio_3 = (RadioButton) findViewById(R.id.option3_button);
RadioButton radio_4 = (RadioButton) findViewById(R.id.option4_button);
if (radio_1.isChecked()) {
pickedAnswer = "a";
radio_1.setChecked(false);
} else if (radio_2.isChecked()) {
pickedAnswer = "b";
radio_2.setChecked(false);
} else if (radio_3.isChecked()) {
pickedAnswer = "c";
radio_3.setChecked(false);
} else if (radio_4.isChecked()) {
pickedAnswer = "d";
radio_4.setChecked(false);
} else {
noSelection = true;
}
}
public void submitAnswer(View view) {
getSelectedAnswer();
if (noSelection) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Please select an answer!");
a_builder.show();
noSelection = false;
} else {
checkAnswer();
nextQuestion();
}
}
public void checkAnswer() {
if (correctAnswer == pickedAnswer) {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Right Answer!");
a_builder.show();
} else {
AlertDialog.Builder a_builder = new AlertDialog.Builder(this);
a_builder.setMessage("Wrong Answer!");
a_builder.show();
}
pickedAnswer = "";
correctAnswer = "";
}
public void restart() {
questionNumber = 0;
//Collections.shuffle(allQuestions.list);
nextQuestion();
}
}
call setChecked(false) on all the buttons after submitting or before showing next question

Linearlayout is not able to remove it's child

One Linearlayout I have created and dynamically I am adding RadioGroup and textView in it. When next time I am calling the method, Textview is getting removed but old radio buttons are not getting removed.
Here is the code:
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.addView(radioButton, params);
radioButton.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}
Here is the image:
I have made some changes in your code.
public void setShippingMethods() {
shippingChargesLayout.removeAllViews();
final RadioGroup radioGroup = new RadioGroup(getActivity());
RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
TextView textView = new TextView(getActivity());
textView.setText("Select Shipping Options:");
shippingChargesLayout.addView(textView);
for (int i = 0; i < shippingDetailsList.size(); i++) {
RadioButton radioButton = new RadioButton(getActivity());
radioButton.setText("" + shippingDetailsList.get(i).getMethodTitle() + "-" + (new SessionManager(getActivity()).getCurrency()) + df.format(shippingDetailsList.get(i).getAmount()));
radioGroup.addView(radioButton);
}
shippingChargesLayout.addView(radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
shipmentCode = shippingDetailsList.get(i - 1).getCarrierCode();
Log.v("carrierCode", "" + shipmentCode);
}
});
checkout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (radioGroup.getCheckedRadioButtonId() == -1) {
Toast.makeText(getActivity(),"Select shipping options.",Toast.LENGTH_LONG).show();
} else {
completeOrder();
}
}
});
}

onClickListener onclicklistener Android Java programming

When i click on the images it doesnt change the display textview, where did i go wrong?
**List<ImageView> fields = new ArrayList<ImageView>();
for(int i = 0; i < 64; i++) {
try{
id = R.id.class.getField("square" + (i+1)).getInt(0);
views.add((ImageView)findViewById(id));
((View) fields).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View fields) {
for(int i=0; i < 64; i++)
{
display = (TextView) findViewById(R.id.textView1);
display.setText("square" + i);
}
}
});
}
catch(Exception e){}
}**
}
}
It looks like you're adding the onClick listener to the ArrayList of views, not the image you added. Change
((View) fields).setOnClickListener
to
findViewById(id).setOnClickListener

Categories