I can't use two OnClickListeners? - java

I have been trying to use two OnClickListeners but I cant figure out how to do it right.
Could anyone help me fix my code?
btnClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
numBase.getText().clear();
numNikotin.getText().clear();
}
btnAdd.setOnClickListener(new View.OnClickListener() { // I basically want this onClick Listener for the btnClear aswell, but I just cant get both to work. If I take away the btnClear setOnCLickListener Event then btnAdd works just fine.
public void onClick(View v) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
}
});
}
}

No you cannot do that. Just split the shared code between two button to another method and call in inside two listener.
private foo() {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
btnClear.setOnClickListener(new View.OnClickListener() {
public void onClick(View paramView) {
numBase.getText().clear();
numNikotin.getText().clear();
foo();
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
foo();
}
});

Try this,
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
numBase.getText().clear();
numNikotin.getText().clear();
btnAdd.performClick();
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
});

try this
use performClick()
public boolean performClick ()
Added in API level 1
Call this view's OnClickListener, if it is defined.
Call this view's OnClickListener, if it is defined. Performs all normal actions associated with clicking: reporting accessibility event, playing a sound, etc
btnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnAdd.performClick();
numBase.getText().clear();
numNikotin.getText().clear();
}
});
than create a separate click listener for btnAdd
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1 = Double.parseDouble(numBase.getText().toString());
num2 = Double.parseDouble(numNikotin.getText().toString());
sum = num1 / 20 * num2;
String resultN = String.format("%.2f%%", Double.toString(sum));
addResult.setText(resultN);
sum = num1 - sum;
String resultB = String.format("%.2f%%", Double.toString(sum));
addResult2.setText(resultB);
}
});

Related

when i press dot button i want that dot button press only one time in input 1?

package com.deitel.calculator;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
double input1 = 0, input2 = 0d ,count=0;
Button btn0, btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn_dot, btn_equal, btn_subtract, btn_multi, btn_add, btn_devision, btn_clear, btn_back;
TextView text_result;
boolean Addition, Subtraction, Multiplication, Devision, decimal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn0 = findViewById(R.id.btn0);
btn1 = findViewById(R.id.btn1);
btn2 = findViewById(R.id.btn2);
btn3 = findViewById(R.id.btn3);
btn4 = findViewById(R.id.btn4);
btn5 = findViewById(R.id.btn5);
btn6 = findViewById(R.id.btn6);
btn7 = findViewById(R.id.btn7);
btn8 = findViewById(R.id.btn8);
btn9 = findViewById(R.id.btn9);
btn_dot = findViewById(R.id.btn_dot);
btn_equal = findViewById(R.id.btn_equal);
btn_add = findViewById(R.id.btn_add);
btn_subtract = findViewById(R.id.btn_subtract);
btn_multi = findViewById(R.id.btn_multi);
btn_devision = findViewById(R.id.btn_devision);
btn_clear = findViewById(R.id.btn_clear);
btn_back = findViewById(R.id.btn_back);
text_result = findViewById(R.id.text_result);
btn0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "0");
}
});
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "1");
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "2");
}
});
btn3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "3");
}
});
btn4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "4");
}
});
btn5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "5");
}
});
btn6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "6");
}
});
btn7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "7");
}
});
btn8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "8");
}
});
btn9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText(text_result.getText() + "9");
}
});
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Addition = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Subtraction = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_multi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Multiplication = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_devision.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (text_result.getText().length() != 0) {
input1 = Float.parseFloat(text_result.getText() + "");
Devision = true;
decimal = false;
text_result.setText(null);
}
}
});
btn_clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
text_result.setText("");
input1 = 0.0;
input1 = 0.0;
}
});
btn_dot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
count=1;
text_result.setText(text_result.getText()+".");
return;
}
else{
text_result.setText(text_result.getText()+"0.");
decimal=true;
}
}
});
btn_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String number = text_result.getText().toString();
int input = number.length();
if (input > 0) {
text_result.setText(number.substring(0, input - 1));
}
}
});
btn_equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
count=0;
if ((Addition || Subtraction || Multiplication || Devision) ) {
if (text_result.getText().toString().trim().equals("")){
input2=0;
return;
}else {
input2 = Float.parseFloat(text_result.getText() + "");
}
}
if (Addition) {
text_result.setText(input1 + input2 + "");
Addition = false;
}
if (Subtraction) {
text_result.setText(input1 - input2 + "");
Subtraction = false;
}
if (Multiplication) {
text_result.setText(input1 * input2 + "");
Multiplication = false;
}
if (Devision) {
text_result.setText(input1 / input2 + "");
Devision = false;
}
}
});
}
}
When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
But this code doesn't meet that requirements - it displays 2.3.4.5 etc..but I want only one dot in one input. When I press dot button I want that dot button press only one time in input 1 like:2.5+3.7 etc.
Here you can manage that with simple flag.
public class MainActivity extends AppCompatActivity {
// IDs of all the numeric buttons
private int[] numericButtons = {R.id.btnZero, R.id.btnOne, R.id.btnTwo, R.id.btnThree, R.id.btnFour, R.id.btnFive, R.id.btnSix, R.id.btnSeven, R.id.btnEight, R.id.btnNine};
// IDs of all the operator buttons
private int[] operatorButtons = {R.id.btnAdd, R.id.btnSubtract, R.id.btnMultiply, R.id.btnDivide};
// TextView used to display the output
private TextView txtScreen;
// Represent whether the lastly pressed key is numeric or not
private boolean lastNumeric;
// Represent that current state is in error or not
private boolean stateError;
// If true, do not allow to add another DOT
private boolean lastDot;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the TextView
this.txtScreen = (TextView) findViewById(R.id.txtScreen);
// Find and set OnClickListener to numeric buttons
setNumericOnClickListener();
// Find and set OnClickListener to operator buttons, equal button and decimal point button
setOperatorOnClickListener();
}
/**
* Find and set OnClickListener to numeric buttons.
*/
private void setNumericOnClickListener() {
// Create a common OnClickListener
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// Just append/set the text of clicked button
Button button = (Button) v;
if (stateError) {
// If current state is Error, replace the error message
txtScreen.setText(button.getText());
stateError = false;
} else {
// If not, already there is a valid expression so append to it
txtScreen.append(button.getText());
}
// Set the flag
lastNumeric = true;
}
};
// Assign the listener to all the numeric buttons
for (int id : numericButtons) {
findViewById(id).setOnClickListener(listener);
}
}
/**
* Find and set OnClickListener to operator buttons, equal button and decimal point button.
*/
private void setOperatorOnClickListener() {
// Create a common OnClickListener for operators
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
// If the current state is Error do not append the operator
// If the last input is number only, append the operator
if (lastNumeric && !stateError) {
Button button = (Button) v;
txtScreen.append(button.getText());
lastNumeric = false;
lastDot = false; // Reset the DOT flag
}
}
};
// Assign the listener to all the operator buttons
for (int id : operatorButtons) {
findViewById(id).setOnClickListener(listener);
}
// Decimal point
findViewById(R.id.btnDot).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastNumeric && !stateError && !lastDot) {
txtScreen.append(".");
lastNumeric = false;
lastDot = true;
}
}
});
// Clear button
findViewById(R.id.btnClear).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
txtScreen.setText(""); // Clear the screen
// Reset all the states and flags
lastNumeric = false;
stateError = false;
lastDot = false;
}
});
// Equal button
findViewById(R.id.btnEqual).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onEqual();
}
});
}
/**
* Logic to calculate the solution.
*/
private void onEqual() {
// If the current state is error, nothing to do.
// If the last input is a number only, solution can be found.
if (lastNumeric && !stateError) {
// Read the expression
String txt = txtScreen.getText().toString();
// Create an Expression (A class from exp4j library)
Expression expression = new ExpressionBuilder(txt).build();
try {
// Calculate the result and display
double result = expression.evaluate();
txtScreen.setText(Double.toString(result));
lastDot = true; // Result contains a dot
} catch (ArithmeticException ex) {
// Display an error message
txtScreen.setText("Error");
stateError = true;
lastNumeric = false;
}
}
}
}

Value not getting updated when making a calculator

I making a simple app in android studio. I have used a Single textview to take in both numbers. I also have buttons made, for the 10 digits, 4 operations and decimal point, and equals.
My app does not read the second number. When I press '=' button, it just displays the first number.
For example, when I put in a number 25, and I press the '+' button, the number gets stored in a float variable res, and the textview is cleared. Now if I put in a second number 11 and I press '=', the output is 25.0
Below, is my code for when I press the + button.
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
}
}
});
and below is my code when I press =
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(Float.toString(res));
res=0;
}
});
num1 and res, both are float, both initialized to 0.
Edit:- adding the full java code.
public class Calculator extends AppCompatActivity {
TextView result;
Button one,two,three,four,five,six,seven,eight,nine,zero,sum,sub,mul,div,decimal,equal;
float num1,num2,res=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
result = findViewById(R.id.result);
one = findViewById(R.id.button_one);
two = findViewById(R.id.button_two);
three = findViewById(R.id.button_three);
four = findViewById(R.id.button_four);
five = findViewById(R.id.button_five);
six = findViewById(R.id.button_six);
seven = findViewById(R.id.button_seven);
eight = findViewById(R.id.button_eight);
nine = findViewById(R.id.button_nine);
zero = findViewById(R.id.button_zero);
sum = findViewById(R.id.button_add);
sub = findViewById(R.id.button_sub);
mul = findViewById(R.id.button_mul);
div = findViewById(R.id.button_div);
decimal = findViewById(R.id.button_decimal);
equal = findViewById(R.id.button_equal);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "1");
}
});
two.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "2");
}
});
three.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "3");
}
});
four.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "4");
}
});
five.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "5");
}
});
six.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "6");
}
});
seven.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "7");
}
});
eight.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "8");
}
});
nine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "9");
}
});
zero.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + "0");
}
});
decimal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(result.getText() + ".");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
}
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res-num1;
result.setText(null);
}
}
});
mul.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res/num1;
result.setText(null);
}
}
});
div.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText() + "");
res=res/num1;
result.setText(null);
}
}
});
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(Float.toString(res));
res=0;
}
});
}
}
Your should also take the second value from the user and make the calculations in every operator function respectively.
There is logical error in your all the operators functions.
Your should add this line in all the operator whenever the specific function in called.
result.setText(num1 - num2 + "");
result.setText(num1 + num2 + "");
and so on!!!
Your are using a wrong technique by making anonymous function for the operation. Please you switch statement of nested if-else.
You are not reading in the value for the second number (right of the operator). Your OnClickListener for the = button does nothing but display res. It doesn't apply the right hand of the operator i.e. the second number
E.g. 1 + 2 = 3
Step 1 press 1
Step 2 press +, the program will get the left of the operator and load it to num1 and add it to res.
Step 3 press 2
Step 4 press =, the program will display res
If you want to see what your program is doing in real time then try using the "Debug" tool where you will be able to step through the program line by line and see what variables are being set to what extra.
use switch case for operators,
let say following are fields;
public static final int plus = 1
public static final int minus= 2
public static final int divide= 3
public static final int multiply= 4
and a variable that hold the current operation,
int currentOperation;
and when some operator button clicked then assign "currentOperation" to that operation
in listener
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(result.getText()==null)
{
result.setText("");
}
else
{
num1 = Float.parseFloat(result.getText().toString());
res=res+num1;
result.setText(null);
num1=0;
currentOperation = plus //plus is public static final int plus = 1
}
}
});
and update '=' lisetener with switch statement,
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1 = Float.parseFloat(result.getText().toString());
switch(currentOperation){
case plus:
res=res+num1;
break;
case minus:
res=res-num1;
break;
case divide:
res=res/num1;
break;
case multiply:
res=res*num1;
break;
}
result.setText(""+ res);
num1=0;
}
});

How to display numbers onto a textview clicked by user?

I created a calculator but I cannot display the numbers onto the TextView like every iphone/android calculator.
For example, if the user clicks 5 + 5. I want 5 + 5 to display on the textview and once you hit equals it displays 10. I've tried different ways to figure this out but I keep getting errors.
ClearBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
TextView output = (TextView) findViewById(R.id.text_view);
output.setText("");
}
});
Button0.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "0");
}
});
Button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "1");
}
});
Button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "2");
}
});
Button3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "3");
}
});
Button4.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "4");
}
});
Button5.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "5");
}
});
Button6.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "6");
}
});
Button7.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "7");
}
});
Button8.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "8");
}
});
Button9.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
textView.setText(textView.getText() + "9");
}
});
// Operation Buttons
addBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(textView == null) {
textView.setText(" ");
} else {
firstValue = Double.parseDouble(textView.getText() + " ");
addition = true;
textView.setText(null);
}
}
});
subBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
subtract = true;
textView.setText(null);
}
});
divideBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
divison = true;
textView.setText(null);
}
});
multiBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
firstValue = Double.parseDouble(textView.getText() + " ");
multiplication = true;
textView.setText(null);
}
});
equalBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
secondValue = Double.parseDouble(textView.getText() + " ");
if(addition == true) {
textView.setText(firstValue + secondValue + " ");
addition = false;
}
if(subtract == true) {
textView.setText(firstValue - secondValue + " ");
subtract = false;
}
if(divison == true) {
textView.setText(firstValue / secondValue + " ");
divison = false;
}
if(multiplication == true) {
textView.setText(firstValue * secondValue + " ");
multiplication = false;
}
}
});
NumberFormatException is an Exception that might be thrown when you
try to convert a String into a number, where that number might be an
int , a float , or any other Java numeric type.
You can use NumberFormat and Double .
Double result = new Double(textView.getText().toString());
NumberFormat nm = NumberFormat.getNumberInstance();
textview.setText(nm.format(result)+ "3");
Hope this helps you .
Can you please try and check whether it works
firstValue = Double.parseDouble(textView.getText().toString().replaceAll(" ",""));
Just a reference since you created multiple onClick listeners which is highly repetitive in your code. I'd recommend taking a look at at Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button? This would allow you to set a switch case for multiple buttons without making multiple onClickListeners. Good luck with your calculator!

Java: how to declare these variables as 'global'/public?

Alright guys, this is a pretty basic question, but it's something I'm not completely sure about. In the example below, I have built a simple calculator with two edittexts (for number entry) and two buttons (add and subtract). At the moment, I am having to declare all the variables/components (e.g. buttons, edittexts etc) in both the btnAdd and btnSub OnClick methods. I mean, this is only a really simple program, but having to re-declare all these variables/components (or whatever you call them?) would obviously be really tedious. You can see the code I've currently got:
Button btnAdd = (Button)findViewById(R.id.btnAdd);
Button btnSub = (Button)findViewById(R.id.btnSub);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView textViewAns = (TextView)findViewById(R.id.TextViewAns);//here
EditText editText1 = (EditText)findViewById(R.id.editText1);//...
EditText editText2 = (EditText)findViewById(R.id.editText2);//...
int num1 = Integer.parseInt(editText1.getText().toString());//...
int num2 = Integer.parseInt(editText2.getText().toString());//...to here
int total = num1 + num2;
textViewAns.setText(Integer.toString(total));
}
});
btnSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextView textViewAns = (TextView)findViewById(R.id.TextViewAns);
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
int num1 = Integer.parseInt(editText1.getText().toString());
int num2 = Integer.parseInt(editText2.getText().toString());
int total = num1 - num2;
textViewAns.setText(Integer.toString(total));
}
});
So you can see all the duplication. What I'm trying to achieve is something like what I'm posting below, though is there anyway that I can do that?
Button btnAdd = (Button)findViewById(R.id.btnAdd);
Button btnSub = (Button)findViewById(R.id.btnSub);
final TextView textViewAns = (TextView)findViewById(R.id.TextViewAns);
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
final int num1 = Integer.parseInt(editText1.getText().toString());
final int num2 = Integer.parseInt(editText2.getText().toString());
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int total = num1 + num2;
textViewAns.setText(Integer.toString(total));
}
});
btnSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int total = num1 - num2;
textViewAns.setText(Integer.toString(total));
}
});
At the moment, I get an error in eclipse saying "Cannot refer to a non-final variable inside an inner class defined in a different method", hence I have added the "final" keyword in front of the variables that I was getting the error for. The problem now though is that whenever I try running the program, it simply freezes as soon as it loads. I'm hopin this will be a quick-fix, though who knows. Anyway, thanks in advance for any answers :)
Could it be a simple as wrapping your code in a loop then using a switching statement at the end to choose between the two options you could save allot of code that way
do {Button btnAdd = (Button)findViewById(R.id.btnAdd);
Button btnSub = (Button)findViewById(R.id.btnSub);
TextView textViewAns = (TextView)findViewById(R.id.TextViewAns);
EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
int num1 = Integer.parseInt(editText1.getText().toString());
int num2 = Integer.parseInt(editText2.getText().toString());
if(btnAdd.setOnClickListener(new View.OnClickListener()) {
#Override
public void onClick(View v) {
int total = num1 + num2;
textViewAns.setText(Integer.toString(total));
break
}
});
else if(btnSub.setOnClickListener(new View.OnClickListener()) {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int total = num1 - num2;
textViewAns.setText(Integer.toString(total));
break;
}
});
else continue;
}while (true)
that's been my experience with writing less code for stuff like that
I think the best solution is to move the code from anonymous class to other class, like:
class Foo{
int things;
void doSth(){}
}
class Bar{
final Foo foo = new Foo();
...
btnSub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
foo.doSth();
}
});
}

Creating android trivia game , cannot proceed to next quest. after it is correctly answered

1.first a random number is selected.
2.the random number corresponds to a case (trivia question) in a switch statement.
3.the case has an onClick() for every possible answer.
4.when the correct answer (and it's corresponding onClick) is selected
I want the dice to roll again and progress the game to the next question.
5.My debug log says tells me the value of this dice rolled. However, I cannot get the view to change for the corresponding case in the switch.
`public class BeginGame extends Activity {
Random generator = new Random();
private static final String TAG = "MyActivity";
boolean dupe = true;
boolean done = false;
int intitializedQuestionValue = -2;
final int rows = 3;
final int columns = 25;
final int RIGHT = -2000;
final int WRONG = -1000;
int score = 0;
int num;
//define array of three rows and 25 columns
int[][] questionArray = new int [rows][columns];
int[] questionNumber = new int [25];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
final Button button0 = (Button) findViewById(R.id.button0);
final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final TextView text = (TextView) findViewById(R.id.TextView01);
//initialize "dice"
for (int i=0; i<25; i++){
questionNumber[i] = -1;
}
for(int i=0; i < columns; i++)
questionArray[0][i] = intitializedQuestionValue;
//set all questions to answered WRONG
for (int i=0; i <columns; i++)
questionArray[1][i] = WRONG;
rollDice();
loop: while (!done)
switch (num) {
case 0:
text.setText("press Virginia0:");
button0.setText("Alabama");
button0.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score -2;
}
});
button1.setText("Mississippi");
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score - 2;
}
});
button2.setText("Philadelphia");
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "fail", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[2][0]= score -2;
}
});
button3.setText("Virginia");
button3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "success", Toast.LENGTH_SHORT).show(); rollDice();
//questionArray[1][0]=RIGHT;
//questionArray[2][0]= score + 5;
}
});
break loop;
case 1:
text.setText("press alabama1:");
button0.setText("Alabama");
button0.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
Toast.makeText(BeginGame.this, "success", Toast.LENGTH_SHORT).show(); rollDice();
}
});
button1.setText("Mississippi");
button1.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
button2.setText("Philadelphia");
button2.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
button3.setText("Virginia");
button3.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
}
});
break loop;
`
your program won't work this way. You have to understand more of android.
The onCreate method is called when an activity is created. ie : when it comes to front. It is executed on the UI thread : a thread that interacts with the user and should never be blocked. So, you are basically blocking the UI thread with your loop (does num ever change by the way ?).
What you should do is remove your while loop from the onCreate method. Just use it to initialize your activity, maybe data structures like questions and widgets and their listeners.
And now give more logic to your listeners : when a button is clicked then change your question and refresh the interface so that the new questions display. Do that until there is no more question to ask.
Do never block the UI Thread, make it free so users can use your app.

Categories

Resources