I was trying to make a rating type questions and i want to set the values in the radio button.. but i can't compute for the sum of the checked buttons.. this is my code..
public class MainActivity extends Activity {
public RadioButton r0,r1,r2,r3,r4,r5,r6,r7,r8,r9;
public RadioGroup rg1,rg2;
public TextView tv1;
public Button btn1;
public static int a,b,c,d,e,a1,b1,c1,d1,e1,total;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
r0 = (RadioButton)findViewById(R.id.radio0);
r1 = (RadioButton)findViewById(R.id.radio1);
r2 = (RadioButton)findViewById(R.id.radio2);
r3 = (RadioButton)findViewById(R.id.radio3);
r4 = (RadioButton)findViewById(R.id.radio4);
r5 = (RadioButton)findViewById(R.id.radio5);
r6 = (RadioButton)findViewById(R.id.radio6);
r7 = (RadioButton)findViewById(R.id.radio7);
r8 = (RadioButton)findViewById(R.id.radio8);
r9 = (RadioButton)findViewById(R.id.radio9);
btn1 = (Button)findViewById(R.id.button1);
tv1 = (TextView)findViewById(R.id.textView7);
rg1 = (RadioGroup)findViewById(R.id.radioGroup1);
rg2 = (RadioGroup)findViewById(R.id.radioGroup2);
btn1.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
switch(rg1.getCheckedRadioButtonId()){
case R.id.radio0:
if (r0.isChecked()){
a =1;
}
break;
case R.id.radio1:
if (r1.isChecked()){
b = 2;
}
break;
case R.id.radio2:
if (r2.isChecked()){
c = 3;
}
break;
case R.id.radio3:
if (r3.isChecked()){
d = 4;
}
break;
case R.id.radio4:
if (r4.isChecked()){
e = 5;
}
break;
}
//no. 2
switch(rg2.getCheckedRadioButtonId()){
case R.id.radio5:
if (r5.isChecked()){
a1=1;
}
break;
case R.id.radio6:
if (r6.isChecked()){
b1 = 2;
}
break;
case R.id.radio7:
if (r7.isChecked()){
c1 = 3;
}
break;
case R.id.radio8:
if (r8.isChecked()){
d1 = 4;
}
break;
case R.id.radio9:
if (r9.isChecked()){
e1 = 5;
}
break;
}
// i want to get the two checked radio button and output the result.. pls help me
total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();
tv1.setText("result: "+total);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Look at this:
total = rg1.getCheckedRadioButtonId() + rg2.getCheckedRadioButtonId();
you are trying to add RadioButtonId's which are radio1, radio2, etc.
There are likely many ways to do this but I think I would create a sum variable that adds the chosen number to it.
case R.id.radio5:
if (r5.isChecked()){
//a1=1;
sum += 1;
}
and finally
tv1.setText("result: "+ sum);
you would need to reset sum each time so it doesn't keep adding to previous.
Related
I am making android calculator. I made some functions but the first problem is double clickable operation.I tried but couldn't. when i click two operations consequently both are appearing on the text view. i'll post my code if you can solve double clickable operation problem please post your code on comment.
public class MainActivity extends AppCompatActivity {
private TextView _screen;
private TextView _result;
private String display = "";
private String currentOperator;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_screen = (TextView) findViewById(R.id.txtScreen);
_result = (TextView) findViewById(R.id.id_result);
}
public void updateScreen() {
_screen.setText(display);
}
public void onClickNumber(View v) {
Button b = (Button) v;
display += b.getText();
updateScreen();
}
public void onClickOperator(View v) {
Button b = (Button) v;
display += b.getText();
currentOperator = b.getText().toString();
updateScreen();
}
public void clear() {
display = "";
currentOperator = "";
}
public void onClickClear(View view) {
clear();
updateScreen();
}
public double operate(String a, String op, String b) {
switch (op) {
case "+":
return Double.valueOf(a) + Double.valueOf(b);
case "-":
return Double.valueOf(a) - Double.valueOf(b);
case "*":
return Double.valueOf(a) * Double.valueOf(b);
case "/":
return Double.valueOf(a) / Double.valueOf(b);
default:
return -1;
}
}
public void onClickEqual(View v) {
String[] operation = display.split(Pattern.quote(currentOperator));
_result.setText(String.valueOf(operate(operation[0], currentOperator, operation[1])));
}
}
what I understand from your question regarding double operation is that Let suppose you are performing operation of + and when you click again for + it gets displayed 2 times on textview (as your method updateScreen suggest). If that is the problem, you can do as mentioned below
public void updateScreen() {
if (screen.getText().toString().equalsIgnoreCase("")) {
screen.setText(display);
} else if (!display.equalsIgnoreCase(screen.getText().toString())) {
screen.setText("");
screen.setText(display);
} else {
//this is the case that means that operator is already set on the text
}
}
Hope that helps you.
For my new app I need to print numbers chosen from a switch case. My switch cases should randomly pick an image and after that, the if statement should check which one was chosen and then change the score. The problem I have is, that my if statements get errors, because of Unreachable Code.
public class MainActivity extends ActionBarActivity {
TextView score;
public int newscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
score = (TextView) findViewById(R.id.textView1);
}
int Id() {
Random rand = new Random();
int imag = rand.nextInt(4);
switch (imag) {
case 0:
score.setText(newscore);
return R.drawable.a;
case 1:
score.setText(newscore);
return R.drawable.b;
case 2:
score.setText(newscore);
return R.drawable.c;
default:
score.setText(newscore);
return R.drawable.d;
}
if(Id() == R.drawable.a){
newscore = newscore+1;
}
if(Id() == R.drawable.b){
newscore = newscore+10;
}
if(Id() == R.drawable.c){
newscore = newscore+100;
}
if(Id() == R.drawable.d){
newscore = newscore+1000;
}
}
}
I would put the switch statement in a method, this is how your Activity should look:
public class MainActivity extends ActionBarActivity {
TextView score;
public int newscore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
score = (TextView) findViewById(R.id.textView1);
Random rand = new Random();
int image = rand.nextInt(4);
int newImage = getImageResourceId(image);
if(newImage == R.drawable.a){
newscore = newscore+1;
score.setText(newscore);
}
if(newImage == R.drawable.b){
newscore = newscore+10;
score.setText(newscore);
}
if(newImage == R.drawable.c){
newscore = newscore+100;
score.setText(newscore);
}
if(newImage == R.drawable.d){
newscore = newscore+1000;
score.setText(newscore);
}
}
public int getImageResourceId(int image) {
switch (image) {
case 0:
return R.drawable.a;
case 1:
return R.drawable.b;
case 2:
return R.drawable.c;
case 3:
return R.drawable.d;
default:
return R.drawable.a;
}
}
}
Further Reading:
Writing your own Java Methods
Returning a value from a Method
You will do switch and always return, because switch-case with default case always returns so:
if(Id() == R.drawable.a){
newscore = newscore+1;
}
if(Id() == R.drawable.b){
newscore = newscore+10;
}
if(Id() == R.drawable.c){
newscore = newscore+100;
}
if(Id() == R.drawable.d){
newscore = newscore+1000;
}
will never run.
i"m learning java and android SDK. for learning propers i built a calculator (not completed yet).
in my code i used ImageView Tags to get the value of the button that the user clicked on:
ImageView button = (ImageView) view;
String buttonTag = button.getTag().toString();
xml:
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/zero"
android:layout_row="17"
android:layout_column="1"
android:tag="0"
android:onClick="calcPad" />
the ImageView Tags values are: "0" - "9", "plus"/"minus" etc..
so i converted it to chars to get the numbers and converted it back to int:
char[] charTag = buttonTag.toCharArray();
for (int z=0; z < charTag.length; z++) {
if (charTag[z] == '0') {number = 0;}
if (charTag[z] == '1') {number = 1;}
...
if (charTag[z] == '9') {number = 9;}
i have tried to use 'try' and 'catch' but the app crash. this what i have tried to do:
try{
num = Integer.getInteger(buttonTag);
} catch(NumberFormatException e) {
Log.i("Exception", e.getMessage());
switch(buttonTag) {
case "Plus":
.....
default:
}
}
what i need to add in order to 'handle' the exception? i tried to add in the catch a switch that get buttonTag value (that is string) but still the same problem.
the complete code (without the try/catch section):
package com.example.idan.calculator;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
double var1 = 0; //holds the first number
double var2 = 0; //holds the second number
int decimalPoint = 0; //indicate if the user clicked on the (.)
String var1string=""; //for processing
String var2string=""; //for processing
double var1Array[]={0,0}; // the return value of var1doublemaker
double var2Array[]={0,0}; // the return value of var2doublemaker
boolean mathAction = false; // indicate if the user clicked on a mathematical button
int mathType = 0; // help me identify between + - * /
char mathValue = 'x'; // for the display
double result = 0; // final result
public double[] var1doubleMaker (String buttonTag, int decimalPoint) {
if (decimalPoint == 1) { //need to add dot to string
var1string = var1string + "." + buttonTag;
var1 = Double.valueOf(var1string);
decimalPoint = 0; // set back to 0
var1Array[0] = var1;
var1Array[1] = decimalPoint;
} else {
var1string = var1string + buttonTag; // add the last number
var1 = Double.valueOf(var1string);
var1Array[0] = var1;
var1Array[1] = decimalPoint;
}
return(var1Array);
}
public double[] var2doubleMaker (String buttonTag, int decimalPoint) {
if (decimalPoint == 1) {
var2string = var2string + "." + buttonTag;
var2 = Double.valueOf(var2string);
decimalPoint = 0;
var2Array[0] = var2;
var2Array[1] = decimalPoint;
} else {
var2string = var2string + buttonTag;
var2 = Double.valueOf(var2string);
var2Array[0] = var2;
var2Array[1] = decimalPoint;
}
return(var2Array);
}
public void calcPad(View view) throws NumberFormatException{
//check which button the user clicked on-
// first: get the ImageView by id
ImageView button = (ImageView) view; // where the user clicked on
String buttonTag = button.getTag().toString(); // hold the tag as string for the switch
char[] charTag = buttonTag.toCharArray();
int number = 111; // 111 - just for initialization
int num = 111;
/*
try{
num = Integer.getInteger(buttonTag);
} catch(NumberFormatException e) {
Log.i("Exception", e.getMessage());
}
*/
Log.i("info - num value:", String.valueOf(num));
//Log.i("info char", String.valueOf(charTag[0]));
char numberToResolve = charTag[0];
switch (numberToResolve) {
case '0':
number = 0;
break;
case '1':
number = 1;
break;
case '2':
number = 2;
break;
case '3':
number = 3;
break;
case '4':
number = 4;
break;
case '5':
number = 5;
break;
case '6':
number = 6;
break;
case '7':
number = 7;
break;
case '8':
number = 8;
break;
case '9':
number = 9;
break;
default:
Log.i("error", "cant resolve number from charTag[]");
}
//Log.i("info number value", String.valueOf(number));
TextView textView = (TextView) findViewById(R.id.calcDisplay); // create an object to print the button that the user clicked
Log.i("info", buttonTag);
// math
if (buttonTag.length() > 1) {
switch(buttonTag) {
case "divid":
mathValue = '/';
mathAction = true;
mathType = 4;
break;
case "multi":
mathValue = '*';
mathAction = true;
mathType = 3;
break;
case "Plus":
mathValue = '+';
mathAction = true;
mathType = 1;
break;
case "minus":
mathValue = '-';
mathAction = true;
mathType = 2;
break;
case "dot":
decimalPoint = 1;
case "equal":
if (mathType == 1) {
result = var1 + var2;
} else if (mathType == 2) {
result = var1 - var2;
} else if (mathType == 3) {
result = var1 * var2;
} else if (mathType == 4) {
result = var1 / var2;
}
String display = Double.toString(result);
textView.setText(display);
break;
case "cc":
var1 = 0;
var2 = 0;
mathAction = false;
decimalPoint = 0;
result = 0;
var1string=""; //for processing
var2string="";
display = Double.toString(result);
textView.setText(display);
break;
default:
Log.i("error", "cant resolve math type from buttonTag");
}
}
//Log.i("info decimalpoint", String.valueOf(decimalPoint));
if (number >= 0 && number <= 9 ) {
// user clicked on a number
//call doubleMaker
if (mathAction) {
//working on var2
double[] var2temp = var2doubleMaker(buttonTag,decimalPoint);
Double dd= var2temp[1];
decimalPoint = dd.intValue(); // set decimalPoint back to 0
// display var1 + math + var2
String display = Double.toString(var1) + Character.toString(mathValue) + Double.toString(var2temp[0]);
textView.setText(display);
} else {
// working on var1
double[] var1temp = var1doubleMaker(buttonTag,decimalPoint);
Double d= var1temp[1];
decimalPoint = d.intValue();
String display = Double.toString(var1temp[0]);
textView.setText(display);
}
}
Log.i("info - var1:", Double.toString(var1));
Log.i("info - var2:", Double.toString(var2));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You just need to pass your string into this : Integer.parseInt("string"). This method help you convert from string to int
ImageView button = (ImageView) view;
String buttonTag = button.getTag().toString();
int number = Integer.parseInt(buttonTag)
I have tested the methods individually by calling them in the case which evaluates the equals button. They work fine. My issue is determining whether the multiplication or addition operator was pressed, and then calling the appropriate method.
I searched online and used an if statement within the case which evaluates the multiplication as such:
case R.id.buttonequals:
if (v.equals(btnmult)) {
Multiplication();
}
else if (v.equals(btnplus)) {
Addition();
}
break;
This doesn't work. It seems logical enough. If the equal button is pressed, then depending on what was pushed, the right method will be called. My full code is below:
public class MainActivity extends Activity {
// variables declared to hold buttons and text field.
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btnc,
btnplus, btnd, btnpnt, btnequal, btnmult;
TextView text;
int num1, num2;
String input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// reference and assign the resources for the view elements
btn0 = (Button) findViewById(R.id.button0);
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
btn3 = (Button) findViewById(R.id.button3);
btn4 = (Button) findViewById(R.id.button4);
btn5 = (Button) findViewById(R.id.button5);
btn6 = (Button) findViewById(R.id.button6);
btn7 = (Button) findViewById(R.id.button7);
btn8 = (Button) findViewById(R.id.button8);
btn9 = (Button) findViewById(R.id.button9);
btnc = (Button) findViewById(R.id.buttonc);
text = (TextView) findViewById(R.id.textView1);
btnd = (Button) findViewById(R.id.buttondel);
btnpnt = (Button) findViewById(R.id.buttonpnt);
btnplus = (Button) findViewById(R.id.buttonplus);
btnequal = (Button) findViewById(R.id.buttonequal);
btnmult = (Button) findViewById(R.id.buttonmult);
// add the click listeners
btn0.setOnClickListener(onClickListener);
btn1.setOnClickListener(onClickListener);
btn2.setOnClickListener(onClickListener);
btn3.setOnClickListener(onClickListener);
btn4.setOnClickListener(onClickListener);
btn5.setOnClickListener(onClickListener);
btn6.setOnClickListener(onClickListener);
btn7.setOnClickListener(onClickListener);
btn8.setOnClickListener(onClickListener);
btn9.setOnClickListener(onClickListener);
btnc.setOnClickListener(onClickListener);
btnd.setOnClickListener(onClickListener);
btnpnt.setOnClickListener(onClickListener);
btnplus.setOnClickListener(onClickListener);
btnequal.setOnClickListener(onClickListener);
btnmult.setOnClickListener(onClickListener);
}
private OnClickListener onClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button0:
text.setText(text.getText().toString()
+ btn0.getText().toString());
break;
case R.id.button1:
text.setText(text.getText().toString()
+ btn1.getText().toString());
break;
case R.id.button2:
text.setText(text.getText().toString()
+ btn2.getText().toString());
break;
case R.id.button3:
text.setText(text.getText().toString()
+ btn3.getText().toString());
break;
case R.id.button4:
text.setText(text.getText().toString()
+ btn4.getText().toString());
break;
case R.id.button5:
text.setText(text.getText().toString()
+ btn5.getText().toString());
break;
case R.id.button6:
text.setText(text.getText().toString()
+ btn6.getText().toString());
break;
case R.id.button7:
text.setText(text.getText().toString()
+ btn7.getText().toString());
break;
case R.id.button8:
text.setText(text.getText().toString()
+ btn8.getText().toString());
break;
case R.id.button9:
text.setText(text.getText().toString()
+ btn9.getText().toString());
break;
case R.id.buttondel:
String contents = text.getText().toString();
if (contents.length() > 1) {
text.setText(contents.substring(0, contents.length() - 1));
} else {
text.setText("");
}
break;
case R.id.buttonc:
text.setText("");
break;
case R.id.button8:
String dot = ".";
String concat = text.getText() + dot;
text.setText(concat);
break;
case R.id.buttonplus:
num1 = Integer.parseInt(text.getText().toString());
num2 = Integer.parseInt(text.getText().toString());
text.setText(text.getText() + "+");
break;
case R.id.buttonmult:
num1 = Integer.parseInt(text.getText().toString());
num2 = Integer.parseInt(text.getText().toString());
text.setText(text.getText() + "x");
break;
case R.id.buttonequals:
if (v.equals(btnmult)) {
Multiplication();
}
else if (v.equals(btnplus)) {
Addition();
}
break;
}
}
};
public void Addition() {
text.setText("");
int total = num1 + num2;
text.setText(Integer.toString(total));
}
public void Multiplication() {
text.setText("");
int total = num1 * num2;
text.setText(Integer.toString(total));
}
#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;
}
Help would be greatly appreciated, and I apologise if the solution is blindly obvious. Thank you all for your time.
Add an onClickListener for your each buttons (multiply, divide etc).
Also add a flag for each as,
boolean multiply = false; //same for rest
which you will have to set to true when they are clicked like,
case R.id.multiply:
multiply = true;
then finally when you chck for onClick event of your = button
public void onClick(View v){
..
case R.id.buttonequals:
if (multiply) {
Multiplication();
}
else if (other flags) {
Addition();
}
break;
}
set a same android:onClick for your all of your Buttons, For example: "clicking"
then use it like this:
public void clicking(View v) {
Button button = (Button) v;
switch (button.getId()) {
case R.id.button0:
text.setText(text.getText().toString()
+ btn0.getText().toString());
break;
case R.id.button1:
text.setText(text.getText().toString()
+ btn1.getText().toString());
break;
and so on...
I'm designing a simple app to count the rows and stitches in crocheting/knitting, but I'm having issues. The actual counting itself is just a modified calculator: display a text field that holds the current number of stitches, and buttons which allow you to add or subtract 1, 5 or 10 to the count. Problem is, punching the buttons in the emulator doesn't work -- the thing compiles without issues and builds without issues, so I'm thinking it's something small I've (not) done.
My Main file:
public class mainCount extends Activity {
private EditText Scr; //Textbox screen
private int NumberBF; //saves screen before pressing button operations
private String Operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Scr = (EditText) findViewById(R.id.stitchCount);
int idList[] = {R.id.stitchMin1, R.id.stitchMin5, R.id.stitchMin10, R.id.stitchPlus1, R.id.stitchPlus5, R.id.stitchPlus10, R.id.clearButton};
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#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_count, menu);
return true;
}
public void mMath(String str){
NumberBF = Integer.parseInt(Scr.getText().toString());
Operation = str;
Scr.setText("0");
}
private void getKeyboard(String str){
String ScrCurrent = Scr.getText().toString();
if(ScrCurrent.equals("0"))
ScrCurrent = "";
ScrCurrent += str;
Scr.setText(ScrCurrent);
}
public void mResult(String str){
int NumAf = Integer.parseInt(Scr.getText().toString());
int result = 0;
if(str.equals("+1")){
result = NumAf + 1;
}
if(str.equals("+5")){
result = NumAf + 5;
}
if(str.equals("+10")){
result = NumAf + 10;
}
if(str.equals("-1")){
result = NumAf - 1;
}
if(str.equals("-5")){
result = NumAf - 5;
}
if(str.equals("-10")){
result = NumAf - 10;
}
Scr.setText(String.valueOf(result));
}
// ButtonListener class
private class ButtonClickListener implements View.OnClickListener{
public void onClick(View v) {
switch (v.getId()) {
case R.id.clearButton: //Clears stitches for this row
Scr.setText("0");
NumberBF = 0;
Operation = "";
break;
case R.id.stitchPlus1:
Operation = "+1";
mResult(Operation);
break;
case R.id.stitchPlus5:
Operation = "+5";
mResult(Operation);
break;
case R.id.stitchPlus10:
Operation = "+10";
mResult(Operation);
break;
case R.id.stitchMin1:
Operation = "-1";
mResult(Operation);
break;
case R.id.stitchMin5:
Operation = "-5";
mResult(Operation);
break;
case R.id.stitchMin10:
Operation = "-10";
mResult(Operation);
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
}
You're not initializing your btnClick ButtonClickListener. Try changing your code to the following:
btnClick = new ButtonClickListener();
for(int id:idList){
View v;
v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}