Android | Radio buttons wont do anything and keep pressed - java

Im trying to make a currency converter homework (i am new to programming)
made everything but the radio button is keeped pressed and isnt doing nothing
(not puting text into the TextView and the radio buttons is locked on "pressed" mode
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_convert);
mResult = (TextView) findViewById(R.id.result);
mToConvert = (EditText) findViewById(R.id.toConvert);
mRadioGroup = (RadioGroup) findViewById(R.id.radioG);
mDollar = (RadioButton) findViewById(R.id.dollar);
Meuro = (RadioButton) findViewById(R.id.euro);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
switch (mRadioGroup.getCheckedRadioButtonId())
{
case R.id.dollar:
Double dollarConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double price = dollarConvert * 1.28;
mDollar.setChecked(true);
Meuro.setChecked(false);
String result = mToConvert.getText().toString();
mResult.setText(result + price);
break;
case R.id.euro:
Double euroConvert = Double.valueOf(mToConvert.getText().toString()); //convert the string to int
double value = euroConvert * 1.28;
mDollar.setChecked(false);
Meuro.setChecked(true);
String result1 = mToConvert.getText().toString();
mResult.setText(result1 + value);
break;
default:;
}
}
});
}
}

you will need to set RadioGroup.setoncheckedchangelistener for RadioGroup to do some Action when check changes event fire.
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup rGroup, int checkedId)
{
//do your code here
}
});

Related

How to update the score for every radioButton of the radioGroup/position the selected?

I have a Quiz app sourcecode with multiple radioGroups in a recyclerView and I want everytime a correct radioButton in a certain position (radioGroup) is selected, it should update a score correct++ and send it to an activity as below.
#Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
int position = getAdapterPosition();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
This works but only on one radioGroup, as in if I select another radioButton from a different position, the score correct is always 1 probably because it is reset to default before onClick funtion is executed again.
My possible solution would be a loop i <= arrayList.size() to contain if (checked) to prevent score correct from being reset to default = 0, but I don't know where to place it and what to contain, because it's not mandatory for the user to select from each radioGroup (unless for the simplest scenario it's a requirement).
How can I update the score for every radioButton of the radioGroup/position the selected?
Adding the for loop solved everything
#Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
int position = getAdapterPosition();
for (int i = 0; i <= position; i++) {
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
}

App Score from checkboxes

I'm coding a quiz app. When I clicked the score button to see if it worked, it showed I got 0 out of 5 right. I put in all the correct answers, but my code didn't tally anything up. What am I missing? I'm not sure what else to add and could really use the guidance as I am a new coder. I appreciate any help you can give.
int correctAnswers = 0;
// Start score
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void answers(View view) {
RadioButton q1 = (RadioButton) findViewById(R.id.yes_radio_button);
Boolean q1RightAnswer = q1.isChecked();
if (q1RightAnswer) {
correctAnswers += 1;
}
CheckBox q2Box1 = (CheckBox) findViewById(R.id.box1_checkbox);
boolean q2Box1RightAnswer = q2Box1.isChecked();
CheckBox q2Box2 = (CheckBox) findViewById(R.id.box2_checkbox);
boolean q2Box2WrongAnswer = q2Box2.isChecked();
CheckBox q2Box3 = (CheckBox) findViewById(R.id.box3_checkbox);
boolean q2Box3RightAnswer = q2Box3.isChecked();
if (q2Box1RightAnswer)
if (q2Box3RightAnswer) {
correctAnswers += 1;
}
if (q2Box2WrongAnswer) {
correctAnswers += 0;
}
RadioButton q3 = (RadioButton) findViewById(R.id.shuri_radio_button);
Boolean q3RightAnswer = q3.isChecked();
if (q3RightAnswer) {
correctAnswers += 1;
}
RadioButton q5 = (RadioButton) findViewById(R.id.two_radio_button);
Boolean q5RightAnswer = q5.isChecked();
if (q5RightAnswer) {
correctAnswers += 1;
}
EditText q4 = (EditText) findViewById(R.id.wakanda);
String q4RightAnswer = q4.getText().toString();
if (q4RightAnswer.equals(correctAnswers)) {
correctAnswers += 1;
} else {
// incorrect, do nothing
}
}
/**
* This method is called when the score button is clicked.
*/
public void submitScore(View view) {
Button nameField = (Button) findViewById(R.id.score);
String score = nameField.getText().toString();
// Show score message as a toast
Toast.makeText(this, "You got " + correctAnswers + "/5 correct!", Toast.LENGTH_LONG).show();
// Exit this method early because there's nothing left to do
return;
}
}
This will never be true
q4RightAnswer.equals(correctAnswers)
You need to compare matching types, not Strings to integers.
Assuming that's what you're trying to do, either parse the string or convert the int to a String.
You'll get zero printed if none of the checkboxes are marked or answers() is never called. For example, what's the difference between the answers method and the submitScore method? Both take a View parameter, so which one is actually assigned to the click event?
I would suggest doing something like
RadioButton q1, q3, q5;
EditText q4;
Checkbox qBox1, qBox2;
Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
q1 = (RadioButton) findViewById(R.id.yes_radio_button);
// assign other views here
submit = (Button) findViewById(R.id.score);
submit.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View v) {
int correctAnswers = 0;
if (q1.isChecked()) correctAnswers += 1;
// TODO: check other inputs
String q4Text = q4.getText().toString();
if (q4Text.equals(String.valueOf(correctAnswers)) {
correctAnswers += 1;
}
// Toast correct answers
}
});
}
Basically, define all views as class level variables, then immediately set them after a content view is available, then only calculate the score when the button is clicked (in other words, wait for user input). Also, reset the score each time the button is clicked.

How to disable the Onclick of RadioButton once it is clicked?

I am creating a quiz app where in it asks a question and gives users options.For options I have used RadioButton So what I want is that once the user clicked any one of the options it should not allow any other options to be clicked but the problem is that it can be still clicked.if possible please write the code.Thanks!
private int Question_no=0;
private Boolean Boolean_Var=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
String[] Question_Array = getResources().getStringArray(R.array.Question1);
TextView Questions = (TextView) findViewById(R.id.Question);
Questions.setText(Question_Array[Question_no]);
String[] Radio_Button1_Array = getResources().getStringArray(R.array.Option_1);
RadioButton Radio_Button1 = (RadioButton) findViewById(R.id.radioButton1);
Radio_Button1.setText(Radio_Button1_Array[Question_no]);
String[] Radio_Button2_Array = getResources().getStringArray(R.array.Option_2);
RadioButton Radio_Button2 = (RadioButton) findViewById(R.id.radioButton2);
Radio_Button2.setText(Radio_Button2_Array[Question_no]);
findViewById(R.id.MenuButton).setVisibility(View.INVISIBLE);
findViewById(R.id.NextButton).setVisibility(View.INVISIBLE);
}
public void On_RadioButton1_Click (View view)
{
if (Boolean_Var == false) {
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_1);
String Answer = Answer_Array[Question_no];
if (Answer.equals(CorrectAns)) {
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton1);
Right_Ans.setTextColor(Color.GREEN);
AnswerSubmitted();
} else {
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton1);
Wrong_Ans.setTextColor(Color.RED);;
GreenTick();
AnswerSubmitted();
}
}
Boolean_Var = true;
}
public void On_RadioButton2_Click(View view)
{
if(Boolean_Var==false)
{
String[] CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String CorrectAns = CorrectAns_Array[Question_no];
String[] Answer_Array = getResources().getStringArray(R.array.Option_2);
String Answer = Answer_Array[Question_no];
if(Answer.equals(CorrectAns))
{
RadioButton Right_Ans = (RadioButton) findViewById(R.id.radioButton2);
Right_Ans.setTextColor(Color.GREEN);
}
else
{
RadioButton Wrong_Ans = (RadioButton) findViewById(R.id.radioButton2);
Wrong_Ans.setTextColor(Color.RED);
GreenTick();
}
}
Boolean_Var=true;
AnswerSubmitted();
}
public void GreenTick()
{
String[] Answer1_Array = getResources().getStringArray(R.array.Option_1);
String Answer1 = Answer1_Array[Question_no];
String[] Answer2_Array = getResources().getStringArray(R.array.Option_2);
String Answer2 = Answer2_Array[Question_no];
String[] Answer3_Array = getResources().getStringArray(R.array.Option_3);
String Answer3 = Answer3_Array[Question_no];
String[] The_CorrectAns_Array = getResources().getStringArray(R.array.Answer1);
String The_CorrectAnsIs = The_CorrectAns_Array[Question_no];
if(The_CorrectAnsIs.equals(Answer1))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton1);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer2))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton2);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else if(The_CorrectAnsIs.equals(Answer3))
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton3);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
else
{
Button Option_with_CorrectAns = (Button) findViewById(R.id.radioButton4);
Option_with_CorrectAns.setTextColor(Color.GREEN);
}
}
public void AnswerSubmitted()
{
findViewById(R.id.MenuButton).setVisibility(View.VISIBLE);
findViewById(R.id.NextButton).setVisibility(View.VISIBLE);
}
}
try this after click on radiobutton :
yourradioButtonId.setClickable(false);
You can use setClickable(false);.For this:
yourradiobutton.setClickable(false);
If I'm understanding correctly, you want to disable the RadioGroup once a certain RadioButton is clicked. Just add an OnCheckedChangedListener and if the id of the RadioButton clicked is the right one, then disable the group by using setEnabled(false). Of course, you can't reenable the RadioGroup unless you have some other logic in your code that will do the re-enabling.
RadioGroup radioGroup = (RadioGroup)findViewById (R.id.radioGroup1);
radioGroup.setOnCheckedChangedListener (new OnCheckedChangedListener(){
public void onCheckedChanged(RadioGroup group, int checkedId)
{
if (checkedId == R.id.radio0)
group.setEnabled(false);
}
});
Edit: It seems that setEnabled() doesn't work, so you should try changing your code so it loops through each RadioButton upon checking radio0:
if (checkedId == R.id.radio0){
for(int i = 0; i < group.getChildCount(); i++){
((RadioButton)rg1.getChildAt(i)).setEnabled(false);
}
}

Use a checkbox to allow the user to save the values in the textviews and editview so they are seen immedietly upon reopening the application.

Very new to android java programming. I created a car payment calculator application for one of my classes and I am trying to create a checkbox that the user can check so that all the values stored in the TextViews and EditViews remain the same when the application is opened again.
Here is my activity:
public class MainActivity extends Activity implements OnClickListener,
OnEditorActionListener, OnItemSelectedListener, OnFocusChangeListener,
OnCheckedChangeListener {
private TextView payment;
private TextView interest;
private EditText principle;
private TextView interestText;
private CheckBox interestBox;
private EditText years;
private TextView apr;
Button plusbutton;
Button minusbutton;
private static String TAG = "CAR";
private Spinner period;
private double aprPercent;
private int t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate");
this.getReferences();
this.setListeners();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void getReferences() {
payment = (TextView) findViewById(R.id.paymentLabel);
interest = (TextView) findViewById(R.id.interestLabel);
apr = (TextView) findViewById(R.id.aprLabel);
aprPercent = Double.parseDouble(apr.getText().toString());
interestText = (TextView) findViewById(R.id.interestText);
interestBox = (CheckBox) findViewById(R.id.checkBox1);
interestBox.setChecked(false);
principle = (EditText) findViewById(R.id.principleEditText);
years = (EditText) findViewById(R.id.yearsEditText);
period = (Spinner) findViewById(R.id.spinner1);
minusbutton = (Button) findViewById(R.id.minusbutton);
plusbutton = (Button) findViewById(R.id.plusbutton);
ArrayAdapter<CharSequence> adapter = ArrayAdapter
.createFromResource(this, R.array.split_array,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
period.setAdapter(adapter);
// principle.setOnFocusChangeListener(this);
Log.d(TAG, "getReferences principle: " + principle.getText()
+ " years:" + years.getText());
}
public void setListeners() { // where the event being consumed will be
// responding
principle.setOnFocusChangeListener(this);
principle.setOnEditorActionListener(this);
years.setOnFocusChangeListener(this);
years.setOnEditorActionListener(this);
interestBox.setOnCheckedChangeListener(this);
period.setOnItemSelectedListener(this);
Log.d(TAG, "setListeners principle: " + principle.getText() + " years:"
+ years.getText());
}
public void setPeriodValue() {
if (period.getSelectedItem().toString().equalsIgnoreCase("Monthly")) {
t = 12;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Quarterly")) {
t = 4;
} else if (period.getSelectedItem().toString()
.equalsIgnoreCase("Annually")) {
t = 1;
}
}
public void updateResults() {
double dblPrinciple = Double
.parseDouble(principle.getText().toString());
double dblYears = Double.parseDouble(years.getText().toString());
double num, denom, dblPayment;
double r = aprPercent / 100;
NumberFormat nf = NumberFormat.getNumberInstance();
NumberFormat curr = NumberFormat.getCurrencyInstance();
apr.setText(nf.format(aprPercent));
setPeriodValue();
num = (r / t);
denom = (1 - Math.pow((1 + num), (t * -dblYears)));
dblPayment = dblPrinciple * (num / denom);
payment.setText(curr.format(dblPayment));
interest.setText(curr
.format((dblPayment * t * dblYears) - dblPrinciple));
}
public void onFocusChange(View v, boolean hasfocus) {
Log.d(TAG, "Focus Change principle: " + principle.getText() + " years"
+ years.getText());
switch (v.getId()) {
case R.id.principleEditText:
case R.id.yearsEditText:
updateResults();
default:
updateResults();
}
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(interestBox.isChecked()) {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
else {
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
if (interestBox.isChecked()!=true){
interest.setVisibility(View.INVISIBLE);
interestText.setVisibility(View.INVISIBLE);
}
else {
interest.setVisibility(View.VISIBLE);
interestText.setVisibility(View.VISIBLE);
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
updateResults();
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
updateResults();
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.minusbutton:
if (aprPercent == 1) {
break;
} else {
aprPercent = aprPercent - 1.0;
updateResults();
break;
}
case R.id.plusbutton:
if (aprPercent == 20) {
break;
} else {
aprPercent = aprPercent + 1.0;
updateResults();
break;
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
updateResults();
}
My guess is that I have to do something with sharedprefs but I'm not exactly sure how to go about it. Any push in the right direction would be great. thank you.
Use getSharedPreferences(...).edit().putString(...).commit() to store values in "onPause()" and again use getSharedPreferences(...).getString(...) to retrieve information in your "onResume()". It's just that easy.
You will have to read how to save your Activity data. In my opinion you should not use checkbox to save this data but save it by default.
To save your data while the screen rotate you will have to check the OnSaveInstanceState and OnRestoreInstanceState like in this post. It will handle the data when rotated too.
To save your data for a longer time (changing of applications, closing application), You will have to use the Android preferences but check how works the lifecycle of an Activity. Basically you will need to save in the OnPause or OnDestroy and reload it in the OnResume or OnCreate.
Concerning the preferences you have a nice tutorial on the Vogella Website
//Get Data
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String url = settings.getString("url", "n/a");
//Save Data
Editor edit = preferences.edit();
edit.putString("username", "new_value_for_user");
edit.apply();

Android Calculating values to pass to onClick method

I think I'm getting confused about the activity lifecycle here, I'm trying to perform a simple weights conversion, nothing spectacular.
the user enters a value, selects whether they want it converted to lbs or kgs and when they press 'Convert' it should spit out the converted values, lookng at the stack trace it seems to have a problem with the parseInt im using.
public class WeightConverter extends Activity implements OnClickListener, OnCheckedChangeListener {
Button convertWeight;
TextView conversionResults;
EditText enterWeight;
RadioGroup weightPicker;
RadioButton radKG, radLB;
double weightValue, convertedWeight;
String weightString;
String measurement;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.weightconverter);
initializeVariables();
}
private void initializeVariables() {
convertWeight = (Button) findViewById(R.id.btnConvertWeight);
conversionResults =(TextView) findViewById(R.id.tvWeightConversion);
enterWeight =(EditText) findViewById(R.id.etWeightToConvert);
weightPicker = (RadioGroup) findViewById(R.id.rgWeightType);
radKG = (RadioButton) findViewById(R.id.radKG);
radLB = (RadioButton) findViewById(R.id.radLB);
convertWeight.setOnClickListener(this);
}
#Override
public void onClick(View v) {
;
switch (v.getId()) {
case R.id.btnConvertWeight:
weightValue = Double.parseDouble(enterWeight.getText().toString());
conversionResults.setText(weightValue + " = " + weightString + measurement);
break;
}
}
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}weightString = String.valueOf(convertedWeight);
}
}
I'm not convinced that your onCheckedChanged method is being called at all (have you seen the code entering it using the debugger?).
Try assigning it to your weightPicker radio group as below instead:
weightPicker.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
public void onCheckedChanged(RadioGroup group, int checkedId)
{
weightValue = Integer.parseInt(enterWeight.getText().toString());
switch (checkedId) {
case R.id.radKG:
convertedWeight = weightValue / 2.2;
measurement = " Kilograms";
break;
case R.id.radLB:
convertedWeight = weightValue * 2.2;
measurement = " Pounds";
break;
}
});
You have weightValue declared as a double but trying to parse integer
double weightValue,
Instead use
weightValue = Double.parseDouble(enterWeight.getText().toString());
I would also suggest error checking on your entered value in case the user enters a non digit

Categories