EDIT: See included error log.
I am trying to create a simple app to roll different sided dice in Android Studio.
This is my code so far:
MainActivity.java
package com.example.thomb.tutorialspoint;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonRoll);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int roll = RollDice(sidesChosen);
TextView tv1 = (TextView)findViewById(R.id.textView);
tv1.setText(roll);
setContentView(tv1);
}
});
}
public int sidesChosen;
public int RollDice(int sides) {
Random r = new Random();
return r.nextInt(sides)+1;
} //method
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButtonD4:
if (checked)
sidesChosen = 4;
break;
case R.id.radioButtonD6:
if (checked)
sidesChosen = 6;
break;
case R.id.radioButtonD8:
if (checked)
sidesChosen = 8;
break;
case R.id.radioButtonD10:
if (checked)
sidesChosen = 10;
break;
case R.id.radioButtonD12:
if (checked)
sidesChosen = 12;
break;
case R.id.radioButtonD20:
if (checked)
sidesChosen = 20;
break;
} //switch
} //method
} //class
This is how the layout looks like:
http://i.imgur.com/IeIbMlz.png
The app crashes when i click the roll button, but I've no idea why. The ID's are all correct and the radio buttons works as expected.
I am using API level 25. I am fairly new to Java, but I am quite familiar with C#, so the problem may lie in the code syntax, although Android Studio reports no errors. Let me know if you need to see the XML for the layout as well.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.thomb.tutorialspoint, PID: 5029
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
at android.view.ViewGroup.addViewInner(ViewGroup.java:4310)
at android.view.ViewGroup.addView(ViewGroup.java:4146)
at android.view.ViewGroup.addView(ViewGroup.java:4087)
at android.view.ViewGroup.addView(ViewGroup.java:4060)
at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:279)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:145)
at com.example.thomb.tutorialspoint.MainActivity$1.onClick(MainActivity.java:25)
at android.view.View.performClick(View.java:5280)
at android.view.View$PerformClick.run(View.java:21239)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
setText() is a overloaded method with two types: one that takes in a String, the other an int. The int here should be string resource ID. This is where your error is. In the code below you're using setText(int) but not passing a valid string resource ID.
int roll = RollDice(sidesChosen);
...
tv1.setText(roll);
Do setText(String.valueOf(roll) to convert it to a String first
EDIT after log post:
The cause of your error is that you're passing 0 to the nextInt() method. This might happen because you've never selected a RadioButton (sidesChosen is 0 by default) or that even after selecting a RadioButton, none of the cases of the switch is entered.
EDIT after second log post: (...)
Remove setContentView(tv1); This is used to attach a layout to an activity. Why are you using it here?
It seems, that you pass 0 to the Random.nextInt() method, which is not allowed.
java.lang.IllegalArgumentException: n <= 0: 0
at java.util.Random.nextInt(Random.java:182)
This happens, if none of your case branches is reached. So it seems, there is something wrong with how you handle the radio button clicks.
Related
Android, java, studio 4.0.1
Trying to code by my own, I am facing an issue which I do not understand from the compiler statements.
Basically, when you click a radio button, a random number is generated in the textview field.
My problem is that the random code written in the case of the clicked radio button is not accepted by the compiler.
Here is the code:
package com.example.random;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
int random;
int random2;
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
random = getRandomNumber(0,1);
MytextView.setText(random.toString());
break;
case R.id.radioButton1to6:
if (checked)
// 1 to 6 code
random2 = getRandomNumber(1,6);
MytextView.setText(random2.toString());
break;
}
}
private int getRandomNumber(int min,int max) {
return (new Random()).nextInt((max - min) + 1) + min;
}
}
I presume that the 2 lines 'Int random;' are wrong, but the compiler seems to want to have them here.
I would have understood that the line 'random = getRandomNumber(0,1);' would have be sufficient in the case part of the code, but the compiler marks 'random' in red.
So far, the compiler says: 'error: int cannot be dereferenced in the MytextView.setText(random.toString());' of the //0 or 1 code part.
I would like to understand what I am missing here. Thanks in advance.
(Or asked simpler: how does one code a random function in a switch/case ?)
ok I found the solution. A possible working code is:
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
TextView MytextView = (TextView)findViewById(R.id.MytextView);
final Random rnd = new Random();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton01:
if (checked)
// 0 or 1 code
MytextView.setText(String.valueOf(rnd.nextInt(3-0) + 0));
break;
case R.id.radioButton1to6:
if (checked)
// Dice 1 to 6 code
MytextView.setText("1 to 6");
break;
case R.id.radioButton1to10:
if (checked)
// 1 to 10 code
MytextView.setText("1 to 10");
break;
}
}
And the 'private int getRandomNumber' at the end can be deleted. No need of it.
I'm making a Quizz App for Android with 10 Questions, all of them with 4 Radio Buttons, and one button at the end to show the score. The problem is when I choose the correct answer it gives 5 points, but if I check another radio button the points will stay 5 and if I press again it sums 5. What is the best way to code this?
Here is the code:
package com.example.android.quizproject;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int points = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
points += 0;
break;
case R.id.questionOneB:
if (checked)
points += 0;
break;
case R.id.questionOneC:
if (checked)
points += 5;
break;
case R.id.questionOneD:
if (checked)
points += 0;
break;
}
}
public void showScore (View view) {
TextView scoreTextView = (TextView) findViewById(R.id.score);
scoreTextView.setText(" " + points);
}
}
You can make use of a counter vvariable which checks if the question has been previousy answered or not. Modify part of your code to this
public void firstRadioButtons (View view){
boolean checked = ((RadioButton) view).isChecked();
int count=0;
switch (view.getId()) {
case R.id.questionOneA:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneB:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
case R.id.questionOneC:
if (checked){
points += 5;
count+=1;}
break;
case R.id.questionOneD:
if (checked)
{
if(count!=0){
points-=5;
count=0;
}
}
break;
}
}
Actually, the way you described it, it's common sense. If you click the right answer once, it will set it to 5, but if you press any other it will add 0 to it.
In general, it will print out 5 since you got the answer correct once, and the other questions are set to 0. There's really nothing to fix here, it's kind of common sense that your variable wouldn't read other than 5. Just like Abhriya said, you could add a counter increment value as done in ( her / his ) example.
I am new to android development and I am trying to develop a calculator with single edit text field. It's not showing any compiler error but it crashes as soon as I press any button. I'm first taking the input for num1 and clearing the edit text field followed by a switch case to detect the operation and collecting the data of the second number.
public class MainActivity extends Activity implements OnClickListener{
EditText ino;
Button btnadd;
Button btnsub;
Button btnmult;
Button btndiv;
Button btneq;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ino=(EditText) findViewById(R.id.ino);
btnadd=(Button) findViewById(R.id.add);
btndiv=(Button) findViewById(R.id.div);
btnsub=(Button) findViewById(R.id.sub);
btnmult=(Button) findViewById(R.id.mult);
btneq=(Button) findViewById(R.id.eq);
btnadd.setOnClickListener((OnClickListener) this);
btnsub.setOnClickListener(this);
btnmult.setOnClickListener(this);
btndiv.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
float num1=0,num2=0,res=0;
String xyz="",ans;
num1=Float.parseFloat(ino.getText().toString());
ino.setText(xyz);
switch(v.getId())
{
case R.id.add:
num2=Float.parseFloat(ino.getText().toString());
res=num2+num1;
ans=Float.toString(res);
break;
case R.id.div:
num2=Float.parseFloat(ino.getText().toString());
ino.setText(xyz);
res=num1/num2;
ans=Float.toString(res);
ino.setText(ans);
break;
case R.id.mult:
num2=Float.parseFloat(ino.getText().toString());
ino.setText(xyz);
res=num2*num1;
ans=Float.toString(res);
ino.setText(ans);
break;
case R.id.sub:
num2=Float.parseFloat(ino.getText().toString());
ino.setText(xyz);
res=num1-num2;
ans=Float.toString(res);
ino.setText(ans);
break;
case R.id.eq:
ans=Float.toString(res);
ino.setText(ans);
break;
default: break;
}
}
}
Here is the copy of stack trace.
12-28 00:49:52.646 2125-2125/com.example.rishabh.calculator2
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.rishabh.calculator2, PID: 2125
java.lang.NumberFormatException: Invalid float: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseFloat(StringToReal.java:308)
at java.lang.Float.parseFloat(Float.java:306)
at com.example.rishabh.calculator2.MainActivity.onClick(MainActivity.java:56)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Your code contains several problems. The first is that Float.parseFloat() will throw a java.lang.NumberFormatException if the string is empty or contains letters. This should be handled with try/catch.
The second problem is that the variables num1, num2 and res cannot be declared locally, because they will be initialized to 0.0 every time a button is clicked.
For the calculator to work it is necessary to remember the operation that is going to be performed when the user clicks the "equals"-button. The previous clicked button can be stored using an int.
The following code is tested and works.
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.view.View.*;
import android.view.View;
public class MainActivity extends Activity implements OnClickListener {
EditText ino;
Button btnadd;
Button btnsub;
Button btnmult;
Button btndiv;
Button btneq;
private float num1 = 0;
private float num2 = 0;
private float res = 0;
private int operation = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ino=(EditText) findViewById(R.id.ino);
btnadd=(Button) findViewById(R.id.add);
btndiv=(Button) findViewById(R.id.div);
btnsub=(Button) findViewById(R.id.sub);
btnmult=(Button) findViewById(R.id.mult);
btneq=(Button) findViewById(R.id.eq);
btnadd.setOnClickListener(this);
btnsub.setOnClickListener(this);
btnmult.setOnClickListener(this);
btndiv.setOnClickListener(this);
btneq.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
String s = ino.getText().toString();
try
{
Float.parseFloat(s);
}
catch (NumberFormatException e)
{
s = "0.0";
}
String xyz="",ans;
ino.setText(xyz);
switch(v.getId())
{
case R.id.eq:
num1=Float.parseFloat(s);
switch (operation) {
case R.id.add:
res = num2 + num1;
break;
case R.id.sub:
res = num2 - num1;
break;
case R.id.mult:
res = num2 * num1;
break;
case R.id.div:
res = num2 / num1;
break;
default:
res = 0;
break;
}
ans=Float.toString(res);
ino.setText(ans);
break;
}
num2 = Float.parseFloat(s);
operation = v.getId();
}
}
From your code it is clear that it will throw java.lang.NumberFormatException exception. If the edit text contains invalid string or empty string the parseFloat method will throw a NumberFormatException.
You are setting the edit text value to empty string in the following code (where xyz is initialised to empty string):
ino.setText(xyz);
After that you are trying to parse the edit text data to float and it will throw an exception. You need to catch those exceptions and properly handle it in your code.
try
{
num1=Float.parseFloat(ino.getText().toString());
}
catch (NumberFormatException e)
{
num1 = 0.0f;
}
(Similar like this, you need to handle all the parseFloat calls)
In your LogCat, I see the following:
java.lang.NumberFormatException: Invalid float: "" at java.lang.StringToReal.invalidReal(StringToReal.java:63)
Many times in your code you are trying to parse a String value and store it as a float, which isn't going to work:
num1=Float.parseFloat(ino.getText().toString());
Instead you should use the following to convert to String to a float:
num1 = Float.valueOf(ino.getText().toString());
I want to create a layout for an Android app that has a numeric keypad and takes four digits to determine if it matches a preset passcode value.
I have seen a few applications use this, so I would have thought that it was a high level widget of some description.
The only thing I can find that's remotely close to what I want is this:
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="numberPassword" >
<requestFocus />
</EditText>
But this isn't really what I'm looking for.
Any input would be awesome and thanks in advance.
EDIT: Here's an image of the iOS dropbox app start screen that I'd like:
I'm beginner in Android.
when I stuck in coding I always use to refer stackoverflow. I have learnt lot of things from stackoverflow.
This is the first time i have dared to answer this question.
Pardon me if I'm wrong and any suggestion regarding coding or the way of writing code in stackoverflow is highly appreciated.
Thank You..
I have did something like this in Fragments..
Take 4 EditText in and set maxLength attribute to 1 in xml for all 4 EditTexts. You can modify EditText as per your requirement.
Note: OnKey method may or may not be not be invoked for DEL(BackSpace) in Stock Android KeyBoard.
public class VerifyCodeFrag extends Fragment implements TextWatcher,View.OnKeyListener,View.OnFocusChangeListener
{
private EditText et_digit1, et_digit2, et_digit3, et_digit4;//In this et_digit1 is Most significant digit and et_digit4 is least significant digit
private int whoHasFocus;
char[] code = new char[4];//Store the digits in charArray.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view=inflater.inflate(R.layout.fragment_verify_code, container, false);
initializeView(view);
et_digit1.requestFocus();//Left digit gets focus after adding of fragment in Container
return view;
}
This method is used to intilize views.
private void initializeView(View view)
{
et_digit1 = (EditText) view.findViewById(R.id.et_vfcode_digit1);
et_digit2 = (EditText) view.findViewById(R.id.et_vfcode_digit2);
et_digit3 = (EditText) view.findViewById(R.id.et_vfcode_digit3);
et_digit4 = (EditText) view.findViewById(R.id.et_vfcode_digit4);
setListners();
}
This method is to set the listeners for each EditTexts.
private void setListners()
{
et_digit1.addTextChangedListener(this);
et_digit2.addTextChangedListener(this);
et_digit3.addTextChangedListener(this);
et_digit4.addTextChangedListener(this);
et_digit1.setOnKeyListener(this);
et_digit2.setOnKeyListener(this);
et_digit3.setOnKeyListener(this);
et_digit4.setOnKeyListener(this);
et_digit1.setOnFocusChangeListener(this);
et_digit2.setOnFocusChangeListener(this);
et_digit3.setOnFocusChangeListener(this);
et_digit4.setOnFocusChangeListener(this);
}
These are the override method of interface OnFocusChangeListner by which I'm checking which EditText currently has focus from where it is useful to fetch number from respective EditText Boxes in afterTextChnged method(override method of TextWatcher).
#Override
public void onFocusChange(View v, boolean hasFocus)
{
switch(v.getId())
{
case R.id.et_vfcode_digit1:
whoHasFocus=1;
break;
case R.id.et_vfcode_digit2:
whoHasFocus=2;
break;
case R.id.et_vfcode_digit3:
whoHasFocus=3;
break;
case R.id.et_vfcode_digit4:
whoHasFocus=4;
break;
default:
break;
}
}
These are the override method of TextWatcher Interface.
Here in this afterTextChanged(override method)
I'm fetching number from EdiTexts storing them in respective index of charArray.
And once the user enter the number in EditText the next EditText will get focus by requestfocus method(Example:et_digit2.requestFocus()).
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
switch (whoHasFocus)
{
case 1:
if(!et_digit1.getText().toString().isEmpty())
{
code[0]= et_digit1.getText().toString().charAt(0);
et_digit2.requestFocus();
}
break;
case 2:
if(!et_digit2.getText().toString().isEmpty())
{
code[1]= et_digit2.getText().toString().charAt(0);
et_digit3.requestFocus();
}
break;
case 3:
if(!et_digit3.getText().toString().isEmpty())
{
code[2]= et_digit3.getText().toString().charAt(0);
et_digit4.requestFocus();
}
break;
case 4:
if(!et_digit4.getText().toString().isEmpty())
{
code[3]= et_digit4.getText().toString().charAt(0);
}
break;
default:
break;
}
}
This method will functionate as delete(BackSpace) key.
In this override method I'm checking whether EditText is empty and DEL(backspace in keypad is pressed).
if true the previous EditText will get focus.
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
if (keyCode == KeyEvent.KEYCODE_DEL)
{
switch(v.getId())
{
case R.id.et_vfcode_digit2:
if (et_digit2.getText().toString().isEmpty())
et_digit1.requestFocus();
break;
case R.id.et_vfcode_digit3:
if (et_digit3.getText().toString().isEmpty())
et_digit2.requestFocus();
break;
case R.id.et_vfcode_digit4:
if (et_digit4.getText().toString().isEmpty())
et_digit3.requestFocus();
break;
default:
break;
}
}
}
return false;
}
}
Sample image.
[1]: https://i.stack.imgur.com/DAc9y.jpg
Did you try adding this:
android:maxLength="4"
android:password="true"
This results in a more password like way.
Update: I'd implement four EditText and make them each maxLength="1".
If you align them horizontally this should work :)
I want to create a layout for an Android app that has a numeric keypad
and takes four digits to determine if it matches a preset passcode
value.
Search for a phone client numeric keypad (e.g. SipDroid (dialpad link), IMSDroid), reconstruct the layout to your needs (e.g. removing #, * and other keys you don't need).
use the suggested attributes from #Tim Messerschmidt
Think out of a secure way to store and retrieve that 4 digit pin code.
In the end I created multiple custom widgets.
There is a Keypad widget. It inherits from TableLayout and has four rows of three buttons. Each button modifies a String - either adding digits or removing them.
Another widget I added was called PINEntry. It takes a single int to specify how many digits have been entered and displays that information accordingly.
I use these two widgets together in another View to recreate the passcode screen.
I am working on an android beginner's tutorial that is a tip calculator. It runs properly, but I was wondering how to replace the else-if statement with a switch statement. Not that it is that important for the purposes of this program, but I'm just trying to wrap my mind around the syntax.
package com.android.tipcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Button;
import android.widget.RadioButton;
import android.view.View;
public class tipcalc extends Activity
{
private EditText txtbillamount;
private EditText txtpeople;
private RadioGroup radiopercentage;
private RadioButton radio15;
private RadioButton radio18;
private RadioButton radio20;
private TextView txtperperson;
private TextView txttipamount;
private TextView txttotal;
private Button btncalculate;
private Button btnreset;
private double billamount = 0;
private double percentage = 0;
private double numofpeople = 0;
private double tipamount = 0;
private double totaltopay = 0;
private double perperson = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls()
{
txtbillamount = (EditText)findViewById(R.id.txtbillamount);
txtpeople = (EditText)findViewById(R.id.txtpeople);
radiopercentage = (RadioGroup)findViewById(R.id.radiopercentage);
radio15 = (RadioButton)findViewById(R.id.radio15);
radio18 = (RadioButton)findViewById(R.id.radio18);
radio20 = (RadioButton)findViewById(R.id.radio20);
txttipamount=(TextView)findViewById(R.id.txttipamount);
txttotal=(TextView)findViewById(R.id.txttotal);
txtperperson=(TextView)findViewById(R.id.txtperperson);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() {
public void onClick (View v){ reset(); }});
}
private void calculate()
{
billamount=Double.parseDouble(txtbillamount.getText().toString());
numofpeople=Double.parseDouble(txtpeople.getText().toString());
if (radio15.isChecked()) {
percentage = 15.00;
} else if (radio18.isChecked()) {
percentage = 18.00;
} else if (radio20.isChecked()) {
percentage = 20.00;
}
tipamount=(billamount*percentage)/100;
totaltopay=billamount+tipamount;
perperson=totaltopay/numofpeople;
txttipamount.setText(Double.toString(tipamount));
txttotal.setText(Double.toString(totaltopay));
txtperperson.setText(Double.toString(perperson));
}
private void reset()
{
txtbillamount.setText("");
txtpeople.setText("");
radiopercentage.clearCheck();
radiopercentage.check(R.id.radio15);
txttipamount.setText("...");
txttotal.setText("...");
txtperperson.setText("...");
}
}
What the people above me said is correct, but for the sake of using a switch statement for the hell of it, you could set an OnCheckedChangedListener on your RadioGroup, then use a class like this:
private class MyCheckedChangedListener implements OnCheckedChangeListener {
#Override
public void onCheckedChanged( RadioGroup group, int checkedId ) {
switch (checkedId) {
case R.id.radio15:
percentage = 15f;
break;
case R.id.radio18:
percentage = 18f;
break;
case R.id.radio20:
percentage = 20f;
break;
}
}
}
A switch is used on one variable - i.e. you have x, which can equal 3,5 or 7. Then you switch x and give several cases - what to do on each possible value (you can also have a default case, when none of the given values match). In your case, you're checking several different variables, so if ... else if ... else is the correct method. You can, of course, make the radio boxes set a shared variable, which you can then switch.
If you're talking about the if-else statements in calculate(), you can't replace it directly with a switch statement. The case values in a switch statement need to be compile-time constants (either integers or enum values). Besides, the if-else here perfectly expresses the logic of what you are trying to do.
You could compute a "switch test value" based on the states of radio15, radio18, and radio20 (say, an integer from 0 to 8, based on the eight possible combinations of values) and switch on that, but I would strongly recommend against such an approach. Not only would it needlessly complicate and obscure the logic of what's going on, you would be cursing yourself if you needed to maintain the code six months from now after you had forgotten the clever trick.