Calculator error in java (classes) - java

I'm trying to make a simple calculator app for android and i'm stuck now. I was planning to make 2 calculators (one basic and the other more advanced, similar to the one built in Windows). The idea was to make it in 3 different classes.
Two classes would contain the "main" code (buttons, layout) and the last one should contain the function which im planning to call (like add, multiply). I managed to finish both calculators in one class but i don't know how to make them call functions from the other class.
PROBLEM: I managed to create the basic calculator and it can call functions from the other class but if i want to add more calculations one after another it wont work right. What I mean is this: Let's say my first number is 1 and my second is 3. It prints the result 4 but if i click add again and put 2 it prints the result 5 instead of 6. Somehow it stores the second variable into the first one and i cannot figure out why :(
Can anyone help me?
Thanks in advance
enter code here
package com.example.simcalc;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainInterface extends Activity implements OnClickListener {
static EditText disp;
static TextView txt1, txt2;
SimFunctions sm;
TextView tx1;
Button btDot, bt1, bt2, bt3, bt4, bt5, bt6, bt7 ,bt8, bt9, bt0, btPlus, btMinus, btDivide, btMult,btEquals, btC;
float num2 =0 , res;
float num1 = 0;
String saveNumber = "";
static char sim ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_interface);
disp = (EditText) findViewById(R.id.enterNumber);
bt1 = (Button) findViewById(R.id.one);
bt2 = (Button) findViewById(R.id.two);
bt3 = (Button) findViewById(R.id.three);
bt4 = (Button) findViewById(R.id.four);
bt5 = (Button) findViewById(R.id.five);
bt6 = (Button) findViewById(R.id.six);
bt7 = (Button) findViewById(R.id.seven);
bt8 = (Button) findViewById(R.id.eight);
bt9 = (Button) findViewById(R.id.nine);
bt0 = (Button) findViewById(R.id.zero);
btPlus = (Button) findViewById(R.id.add);
btMinus = (Button) findViewById(R.id.sub);
btMult = (Button) findViewById(R.id.mult);
btDivide = (Button) findViewById(R.id.div);
btC = (Button) findViewById (R.id.can);
btDot = (Button) findViewById(R.id.decimal);
btEquals = (Button) findViewById(R.id.equal);
txt1 = (TextView) findViewById(R.id.textView1);
txt2 = (TextView) findViewById(R.id.textView2);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
bt3.setOnClickListener(this);
bt4.setOnClickListener(this);
bt5.setOnClickListener(this);
bt6.setOnClickListener(this);
bt7.setOnClickListener(this);
bt8.setOnClickListener(this);
bt9.setOnClickListener(this);
bt0.setOnClickListener(this);
btPlus.setOnClickListener(this);
btMinus.setOnClickListener(this);
btDivide.setOnClickListener(this);
btMult.setOnClickListener(this);
btC.setOnClickListener(this);
btDot.setOnClickListener(this);
btEquals.setOnClickListener(this);
disp.setText("0");
sm = new SimFunctions();
}
#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_interface, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()){
case R.id.one:
saveNumber += "1";
disp.setText(saveNumber);
break;
case R.id.two:
saveNumber += "2";
disp.setText(saveNumber);
break;
case R.id.three:
saveNumber += "3";
disp.setText(saveNumber);
break;
case R.id.four:
saveNumber += "4";
disp.setText(saveNumber);
break;
case R.id.five:
saveNumber += "5";
disp.setText(saveNumber);
break;
case R.id.six:
saveNumber += "6";
disp.setText(saveNumber);
break;
case R.id.seven:
saveNumber += "7";
disp.setText(saveNumber);
break;
case R.id.eight:
saveNumber += "8";
disp.setText(saveNumber);
break;
case R.id.nine:
saveNumber += "9";
disp.setText(saveNumber);
break;
case R.id.zero:
saveNumber += "0";
disp.setText(saveNumber);
break;
case R.id.decimal:
if (saveNumber.contains(".")){
break;
}
else{
saveNumber += ".";
disp.setText(saveNumber);
break;
}
case R.id.mult:
sim = '*';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.add:
sim = '+';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.div:
sim = '/';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.sub:
sim = '-';
if (saveNumber != ""){
num1 = Float.parseFloat(saveNumber);
saveNumber = "";
break;}
else{
break;}
case R.id.equal:
sm.equals(num1, saveNumber, sim);
break;
case R.id.can:
saveNumber = "";
disp.setText(saveNumber);
break;
}
}
}
package com.example.simcalc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SimFunctions extends MainInterface {
public void equals(float num1, String saveNumber, char simbol){
String ds = "";
if ( saveNumber != "") {
try{
num2 = Float.parseFloat(saveNumber);}
catch(NumberFormatException e){
e.printStackTrace();
}
}
else {
num2 = 0;}
switch (simbol){
case ('*'):
res = num1 * num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
case ('+'):
ds = Float.toString(num1);
txt1.setText(ds);
ds = Float.toString(num2);
txt2.setText(ds);
res = num1 + num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
case ('/'):
res = num1 / num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";`enter code here`
ds = "";
break;
enter code here
case ('-'):
res = num1 - num2;
num1 = res;
ds = Float.toString(res);
disp.setText(ds);
saveNumber = "";
ds = "";
break;
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/testBlack"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainInterface" >
<EditText
android:id="#+id/enterNumber"
android:layout_width="match_parent"
android:layout_height="110dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#color/scoreColor"
android:inputType="numberDecimal" />
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout2"
android:layout_alignParentBottom="true"
android:layout_marginBottom="86dp"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/seven"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="7" />
<Button
android:id="#+id/eight"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="8" />
<Button
android:id="#+id/nine"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="9" />
<Button
android:id="#+id/div"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="/" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_alignLeft="#+id/enterNumber"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/four"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="4" />
<Button
android:id="#+id/five"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="5" />
<Button
android:id="#+id/six"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="6" />
<Button
android:id="#+id/mult"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="*" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout2"
android:layout_below="#+id/enterNumber"
android:layout_marginTop="20dp"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/one"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="1" />
<Button
android:id="#+id/two"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="2" />
<Button
android:id="#+id/three"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="3" />
<Button
android:id="#+id/sub"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignParentBottom="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingTop="20dp" >
<Button
android:id="#+id/can"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="c" />
<Button
android:id="#+id/zero"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="0" />
<Button
android:id="#+id/equal"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="=" />
<Button
android:id="#+id/add"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<Button
android:id="#+id/decimal"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="." />
</LinearLayout>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout3"
android:layout_alignParentLeft="true"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout3"
android:layout_toRightOf="#+id/textView1"
android:text="TextView" />
</RelativeLayout>

You are putting the result of the operation into the global var 'num1'.
The next time you press '+' you overwrite that value with the previous saveNumber value.
So your logic is like this:
1 -> savenumber = 1
+ -> num1 = 1
3 -> savenumber = 3
= -> num2 = savenumber
-> res = num1 + num2
-> num1 = res
+ -> num1 = savenumber = 3
2 -> savenumber = 2
= -> num2 = savenumber
-> res = num1 + num2
= 3 + 2

Related

Android - How do I keep a button clicked (Selected)?

I am trying to build a calculator with two TextView fields for the two numbers. I figured out how to input the numbers using an "in-app" number pad for the top number, Operand 1 [textView] (I know it would be easier using an EditText but this is for an assignment). I am having trouble switching to the second textView, Operand 2 [textView2].
When I am done input the number for textView, I want to switch to textView2 (using the plus, minus, mult, and/or div Buttons) and continue to enter in the numbers so I can use it for calculations.
Here is an Image of what my app looks like. Please ignore the stars, progress bar, and raido buttons as they are apart of the assignment but not relevent to the calculator.
Do you have any suggestion about how I can do this?
Android Code
package com.example.tristan.assn2;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.view.View.OnClickListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
String operand1 = "";
String operand2 = "";
String oneS = "1";
String twoS = "2";
String threeS = "3";
String fourS = "4";
String fiveS = "5";
String sixS = "6";
String sevenS = "7";
String eightS = "8";
String nineS = "9";
String zeroS = "0";
String dotS = ".";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void sendMessage(View view)
{
Button clickedButton = (Button) view;
Button one = (Button) findViewById(R.id.button);
Button two = (Button) findViewById(R.id.button2);
Button three = (Button) findViewById(R.id.button3);
Button four = (Button) findViewById(R.id.button4);
Button five = (Button) findViewById(R.id.button5);
Button six = (Button) findViewById(R.id.button6);
Button seven = (Button) findViewById(R.id.button7);
Button eight = (Button) findViewById(R.id.button8);
Button nine = (Button) findViewById(R.id.button9);
Button zero = (Button) findViewById(R.id.button10);
Button dot = (Button) findViewById(R.id.button11);
Button clear = (Button) findViewById(R.id.button12);
Button plus = (Button) findViewById(R.id.button17);
Button minus = (Button) findViewById(R.id.button15);
Button mult = (Button) findViewById(R.id.button19);
Button div = (Button) findViewById(R.id.button21);
Button sr = (Button) findViewById(R.id.button16);
Button fac = (Button) findViewById(R.id.button20);
Button dd = (Button) findViewById(R.id.button22);
Button equal = (Button) findViewById(R.id.button23);
//------------------------------------------------------------------------------------------
TextView textView = (TextView) findViewById(R.id.textView);
TextView textView2 = (TextView) findViewById(R.id.textView2);
//OPERAND1
if(clickedButton == minus) {
operand1 = "-";
list1.add(operand1);
}
if (clickedButton == one) {
operand1 = oneS;
list1.add(operand1);
}
if (clickedButton == two) {
operand1 = twoS;
list1.add(operand1);
}
if (clickedButton == three) {
operand1 = threeS;
list1.add(operand1);
}
if (clickedButton == four) {
operand1 = fourS;
list1.add(operand1);
}
if (clickedButton == five) {
operand1 = fiveS;
list1.add(operand1);
}
if (clickedButton == six) {
operand1 = sixS;
list1.add(operand1);
}
if (clickedButton == seven) {
operand1 = sevenS;
list1.add(operand1);
}
if (clickedButton == eight) {
operand1 = eightS;
list1.add(operand1);
}
if (clickedButton == nine) {
operand1 = nineS;
list1.add(operand1);
}
if (clickedButton == zero) {
operand1 = zeroS;
list1.add(operand1);
}
if (clickedButton == dot) {
operand1 = dotS;
list1.add(operand1);
}
//Builds String from ArrayList
StringBuilder sb1 = new StringBuilder();
for (String s1 : list1) {
sb1.append(s1);
}
//STRING NUMBER
String output1 = sb1.toString();
textView.setText(output1);
//NEED TO CONVERT TO DOUBLE*****************
//IF plus, minus, mult, div is pressed, switch to Operand 2 and input numbers
if(clickedButton == plus || clickedButton == minus || clickedButton == mult || clickedButton == div) {
if (clickedButton == one) {
operand2 = oneS;
list2.add(operand2);
}
if (clickedButton == two) {
operand2 = twoS;
list2.add(operand2);
}
if (clickedButton == three) {
operand2 = threeS;
list2.add(operand2);
}
if (clickedButton == four) {
operand2 = fourS;
list2.add(operand2);
}
if (clickedButton == five) {
operand2 = fiveS;
list2.add(operand2);
}
if (clickedButton == six) {
operand2 = sixS;
list2.add(operand2);
}
if (clickedButton == seven) {
operand2 = sevenS;
list2.add(operand2);
}
if (clickedButton == eight) {
operand2 = eightS;
list2.add(operand2);
}
if (clickedButton == nine) {
operand2 = nineS;
list2.add(operand2);
}
if (clickedButton == zero) {
operand2 = zeroS;
list2.add(operand2);
}
if (clickedButton == dot) {
operand2 = dotS;
list2.add(operand2);
}
//Builds String from ArrayList
StringBuilder sb2 = new StringBuilder();
for (String s2 : list2) {
sb2.append(s2);
}
//STRING NUMBER
String output2 = sb2.toString();
textView2.setText(output2);
}
}
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tristan.assn2.MainActivity">
<Button
android:text="/"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button21"
android:fontFamily="sans-serif-medium"
android:layout_alignBaseline="#+id/button18"
android:layout_alignBottom="#+id/button18"
android:layout_toRightOf="#+id/button18"
android:layout_alignRight="#+id/button15"
android:layout_alignEnd="#+id/button15"
android:onClick="sendMessage"/>
<Button
android:text="3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button3"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Button
android:text="2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:layout_alignBaseline="#+id/button"
android:layout_alignBottom="#+id/button"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:onClick="sendMessage"/>
<Button
android:text="1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button"
android:layout_marginBottom="61dp"
android:layout_alignParentBottom="true"
android:layout_toLeftOf="#+id/button2"
android:layout_toStartOf="#+id/button2"
android:onClick="sendMessage"/>
<Button
android:text="4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button4"
android:layout_above="#+id/button2"
android:layout_alignLeft="#+id/button11"
android:layout_alignStart="#+id/button11"
android:onClick="sendMessage"/>
<Button
android:text="5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button2"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:id="#+id/button5"
android:onClick="sendMessage"/>
<Button
android:text="6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button5"
android:layout_toRightOf="#+id/button2"
android:layout_toEndOf="#+id/button2"
android:id="#+id/button6"
android:onClick="sendMessage"/>
<Button
android:text="7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button7"
android:layout_above="#+id/button4"
android:layout_alignLeft="#+id/button4"
android:layout_alignStart="#+id/button4"
android:onClick="sendMessage"/>
<Button
android:text="8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/button7"
android:layout_toRightOf="#+id/button4"
android:layout_toEndOf="#+id/button4"
android:id="#+id/button8"
android:onClick="sendMessage"/>
<Button
android:text="9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/button6"
android:layout_toRightOf="#+id/button5"
android:id="#+id/button9"
android:layout_alignTop="#+id/button8"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Button
android:text="0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button3"
android:layout_toLeftOf="#+id/button3"
android:layout_toStartOf="#+id/button3"
android:id="#+id/button10"
android:onClick="sendMessage"/>
<Button
android:text="."
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button10"
android:layout_toLeftOf="#+id/button2"
android:id="#+id/button11"
android:layout_below="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="87dp"
android:layout_marginStart="87dp"
android:layout_marginTop="47dp"
android:onClick="sendMessage"/>
<Button
android:text="-"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button15"
android:layout_alignTop="#+id/button7"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="41dp"
android:layout_marginStart="41dp"
android:layout_toLeftOf="#+id/button4"
android:layout_toStartOf="#+id/button4"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:onClick="sendMessage"/>
<Button
android:text="+"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button17"
android:layout_alignBaseline="#+id/button15"
android:layout_alignBottom="#+id/button15"
android:layout_toStartOf="#+id/button4"
android:layout_toLeftOf="#+id/button4"
android:layout_marginRight="47dp"
android:layout_marginEnd="47dp"
android:onClick="sendMessage" />
<Button
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button18"
android:layout_below="#+id/button17"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/button17"
android:layout_alignEnd="#+id/button17"
android:fontFamily="sans-serif-medium"
android:onClick="sendMessage"/>
<Button
android:text="x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button19"
android:layout_below="#+id/button17"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignRight="#+id/button17"
android:layout_alignEnd="#+id/button17"
android:fontFamily="sans-serif-medium"
android:onClick="sendMessage"/>
<Button
android:text="sr"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button16"
android:fontFamily="sans-serif-medium"
android:layout_below="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/button20"
android:layout_toStartOf="#+id/button20"
android:onClick="sendMessage"/>
<Button
android:text="!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button20"
android:fontFamily="sans-serif-medium"
android:layout_below="#+id/button21"
android:layout_alignLeft="#+id/button15"
android:layout_alignStart="#+id/button15"
android:layout_alignRight="#+id/button21"
android:layout_alignEnd="#+id/button21"
android:onClick="sendMessage"/>
<Button
android:text="DD - DMS"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/button11"
android:layout_toStartOf="#+id/button"
android:id="#+id/button22"
android:layout_alignRight="#+id/button20"
android:layout_alignEnd="#+id/button20"
android:onClick="sendMessage"/>
<TextView
android:hint="Operand 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView"
android:layout_toLeftOf="#+id/button5"
android:layout_toStartOf="#+id/button5" />
<TextView
android:hint="Operand 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="13dp"
android:id="#+id/textView2"
android:layout_toLeftOf="#+id/button8"
android:layout_toStartOf="#+id/button8" />
<TextView
android:hint="Results"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/textView3"
android:layout_toRightOf="#+id/textView"
android:layout_toEndOf="#+id/textView" />
<RatingBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ratingBar"
android:isIndicator="false"
android:layout_centerVertical="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/progressBar"
android:layout_alignBottom="#+id/ratingBar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="12dp"
android:layout_marginStart="12dp" />
<RadioButton
android:text="Use for Operand 1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/radioButton"
android:layout_below="#+id/button23"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<RadioButton
android:text="Use for Operand 2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/radioButton"
android:layout_alignLeft="#+id/radioButton"
android:layout_alignStart="#+id/radioButton"
android:id="#+id/radioButton2" />
<Button
android:text="="
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button23"
android:layout_alignTop="#+id/textView2"
android:layout_toRightOf="#+id/textView2"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="sendMessage"/>
<Spinner
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/spinner"
android:layout_below="#+id/radioButton2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="C"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/button12"
android:layout_alignBaseline="#+id/button10"
android:layout_alignBottom="#+id/button10"
android:layout_toRightOf="#+id/button8"
android:layout_toEndOf="#+id/button8"
android:onClick="sendMessage"/>
</RelativeLayout>
You have to listen the key clicks after the plus/minus/.. button clicks occurs. Use a flag. set the flag 1 when plus/minus/.. or textview2 gets clicked and change the textview to textview2 and list1 to list2. Do the vice versa when textview1 is clicked.
you can do something like this :
public class YourActivityName extends AppCompatActivity {
TextView operand1, operand2,result,tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dd);
operand1 = (TextView) findViewById(R.id.textView);
operand2 = (TextView) findViewById(R.id.textView2);
result= (TextView) findViewById(R.id.textView3);
tv=operand1;
}
public void sendMessage(View v) {
if (v.getId() == R.id.button19 || v.getId() == R.id.button15 || v.getId() == R.id.button17 || v.getId() == R.id.button21 || v.getId() == R.id.button18) {
tv=operand2;
}
if(v.getId()==R.id.button7){
tv.setText(tv.getText()+"7");
}
if(v.getId()==R.id.button8){
tv.setText(tv.getText()+"8");
}
if(v.getId()==R.id.button23){
int op1=Integer.parseInt(operand1.getText().toString());
int op2=Integer.parseInt(operand2.getText().toString());
op2+=op1;
result.setText(op2+"");
tv=operand1;
operand1.setText("");
operand2.setText("");
}
}
}
this is code only for having addition on pressing '=' button and for taking input only from button '7' and '8' you need to and functionality for other buttons and operations ..but it should solve your problem of changing textview for input...
you can also do by means of flags . as suggested by #Code-Apprentice ...
You should toggle a boolean flag whenever the user clicks an operator button. Then when the user clicks a number button, check this flag to determine which operand is being used.
In conjunction with this flag, you can also have a variable like TextView currentTextView which is assigned to refer to the currently used TextView. Then whenever the user clicks an operator button, assign this variable to the other TextView. This strategy will make it so you only need if statements in the OnClickListeners for the operator buttons. You won't need any if statements in the OnClickListeners for the number buttons.
p.s. Note that every number button already displays the numerical character. You can use this fact to remove nearly all of the if...else chain in your click listener.
p.p.s. You should consider writing different OnClickListeners for each button. With the previously mentioned strategy, you can have a single listener for all the number buttons, but I still suggest creating a different listener for each operator button.

can't use findViewById id cannot resolved

I can't figured it out in my project.
I already save the .xml, but the findViewById cannot find my Id. All other findViewById are fine, but the error is on the Apple one. I tried to rename the id, but it didn't work. Here is my code
package com.flaternity.fasterbrain;
import android.annotation.SuppressLint;
import com.flaternity.fasterbrain.*;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
public class Game extends ActionBarActivity {
TextView Timer, TEST, Score, GAMEOVER, yourScore, TimerText, TIMEUP;
Button Left, Right, BACKBTN;
ImageView Apple;
int RanSoal, whichTrue = 0, EngSoal;
static int score=0;
static int curGame;//0=Math 1=English
String[] EngTest={
"I __ sick",//0
"I __ Happy yerterday",
"Books __ available in BookStore",
"He __ Games yesterday",
"Minions __ Bananas",
"She __ Books",
"How __ water do you have?",//6
"your __ is Nice",
"__ love Game",
"I am __ than you",
};
String[] Mathtest ={
"2x2=__",//1 [0]
"4:__=4",
"4+5=__",
"5X5=__",
"5X__=45",//5 [4]
"35-5=__",
"5:5=__",
"2-5=__",
"2X(-5)=__",
"2+__=1",//10[9]
"5-5=__",
"2+1=__",
"4:__=8",
"4:2=__",
"3-2=__",//15[14]
"9X4=__",
"10:__=80",
"9X__=36",
"8X4=__",
"3X3=__"//20[19]
};
CountDownTimer timer = new CountDownTimer(3000,1000){
#Override
public void onTick(long millisUntilFinished) {
Timer.setText(""+millisUntilFinished / 1000);
}
#Override
public void onFinish() {
TimeUP();
Timer.setText("0");
}
};
private void MakeSoalMath(){
RanSoal = (int)(Math.random()*19);
TEST.setText(""+Mathtest[RanSoal]);
switch(RanSoal){
case 0:
Left.setText("4");//True
Right.setText("8");
whichTrue = 0;
break;
case 1:
Left.setText("1");//True
Right.setText("4");
whichTrue = 0;
break;
case 2:
Left.setText("9");//True
Right.setText("20");
whichTrue = 0;
break;
case 3:
Left.setText("25");//True
Right.setText("10");
whichTrue = 0;
break;
case 4:
Left.setText("9");//True
Right.setText("5");
whichTrue = 0;
break;
case 5:
Left.setText("30");//True
Right.setText("7");
whichTrue = 0;
break;
case 6:
Left.setText("1");//True
Right.setText("25");
whichTrue = 0;
break;
case 7:
Left.setText("-3");//True
Right.setText("3");
whichTrue = 0;
break;
case 8:
Left.setText("-10");//True
Right.setText("10");
whichTrue = 0;
break;
case 9:
Left.setText("-1");//True
Right.setText("1");
whichTrue = 0;
break;
case 10:
Left.setText("10");
Right.setText("0");//True
whichTrue = 1;
break;
case 11:
Left.setText("-3");
Right.setText("3");//True
whichTrue = 1;
break;
case 12:
Left.setText("2");
Right.setText("1/2");//True
whichTrue = 1;
break;
case 13:
Left.setText("8");
Right.setText("2");//True
whichTrue = 1;
break;
case 14:
Left.setText("3");
Right.setText("1");//True
whichTrue = 1;
break;
case 15:
Left.setText("5");
Right.setText("36");//True
whichTrue = 1;
break;
case 16:
Left.setText("8");
Right.setText("1/8");//True
whichTrue = 1;
break;
case 17:
Left.setText("27");
Right.setText("4");//True
whichTrue = 1;
break;
case 18:
Left.setText("12");
Right.setText("32");//True
whichTrue = 1;
break;
case 19:
Left.setText("6");
Right.setText("9");//True
whichTrue = 1;
break;
}
}
private void Benar(){
if(curGame == 0){
MakeSoalMath();
}
score++;
Score.setText(""+score);
timer.cancel();
timer.start();
}
private void Salah(){
BACKBTN.setVisibility(View.VISIBLE);
yourScore.setVisibility(View.VISIBLE);
GAMEOVER.setVisibility(View.VISIBLE);
Timer.setVisibility(View.INVISIBLE);
TEST.setVisibility(View.INVISIBLE);
Score.setVisibility(View.INVISIBLE);
Left.setVisibility(View.INVISIBLE);
Right.setVisibility(View.INVISIBLE);
TimerText.setVisibility(View.INVISIBLE);
yourScore.setText("your score:" + score);
timer.cancel();
}
private void TimeUP(){
BACKBTN.setVisibility(View.VISIBLE);
yourScore.setVisibility(View.VISIBLE);
TIMEUP.setVisibility(View.VISIBLE);
Timer.setVisibility(View.INVISIBLE);
TEST.setVisibility(View.INVISIBLE);
Score.setVisibility(View.INVISIBLE);
Left.setVisibility(View.INVISIBLE);
Right.setVisibility(View.INVISIBLE);
TimerText.setVisibility(View.INVISIBLE);
yourScore.setText("your score:" + score);
timer.cancel();
}
private void masukGame(){
Timer=(TextView)findViewById(R.id.Timer);
TEST=(TextView)findViewById(R.id.TEST);
Score=(TextView)findViewById(R.id.Score);
Left=(Button)findViewById(R.id.LeftAnswer);
Right=(Button)findViewById(R.id.RightAnswer);
BACKBTN=(Button)findViewById(R.id.BACKTom);
GAMEOVER=(TextView)findViewById(R.id.GAMEOVER);
yourScore=(TextView)findViewById(R.id.yourScore);
TimerText=(TextView)findViewById(R.id.TimeText);
TIMEUP=(TextView)findViewById(R.id.TIMEUP);
Apple=(ImageView)findViewById(R.id.Apple);
BACKBTN.setVisibility(View.INVISIBLE);
GAMEOVER.setVisibility(View.INVISIBLE);
yourScore.setVisibility(View.INVISIBLE);
TIMEUP.setVisibility(View.INVISIBLE);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
masukGame();
timer.start();
Right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(whichTrue == 1){
Benar();
}else{
Salah();
}
}
});
Left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(whichTrue == 0){
Benar();
}else{
Salah();
}
}
});
BACKBTN.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent myIA = new Intent(Game.this, MainMenu.class);
Game.this.startActivity(myIA);
}
});
//Math
if(curGame==0){
MakeSoalMath();
}else{//ENGLISH
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, 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);
}
}
Here is xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.flaternity.fasterbrain.Game" >
<TextView
android:id="#+id/Timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textSize="28sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/TEST"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="50dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:textSize="28sp"
android:textColor="#000000"
/>
<TextView
android:id="#+id/Score"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal = "true"
android:textColor="#000000"
android:textSize="28sp"
android:text="0"
/>
<TextView
android:id="#+id/TimeText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textSize="28sp"
android:textColor="#000000"
android:text="Time Left:" />
<Button
android:id="#+id/LeftAnswer"
android:layout_width="140dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="80dp"
android:textColor="#000000"
android:textSize="32sp"
/>
<Button
android:id="#+id/RightAnswer"
android:layout_width="140dp"
android:layout_height="150dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="80dp"
android:layout_alignParentRight="true"
android:textColor="#000000"
android:textSize="32sp"
/>
<TextView
android:id="#+id/GAMEOVER"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#000000"
android:textSize="40sp"
android:text="GAME OVER"
/>
<TextView
android:id="#+id/TIMEUP"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:textColor="#000000"
android:textSize="40sp"
android:text="TIME IS UP"
/>
<Button
android:id="#+id/BACKTom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical|center_horizontal"
android:layout_alignParentBottom="true"
android:layout_marginBottom="5dp"
android:textColor="#000000"
android:textSize="20sp"
android:text="Back"
/>
<TextView
android:id="#+id/yourScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:textColor="#000000"
android:textSize="28sp"
android:text="your score :"
/>
<ImageView
android:id="#+id/Apple"
android:layout_width="150dp"
android:layout_height="150dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal ="true"
android:layout_marginTop="40dp"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:src="#drawable/Apple" />
</RelativeLayout>
The Error is on Apple=(ImageView)findViewById(R.id.Apple);
but somehow I noticed the difference before the Problem and After the Problem. Before the problem, when I modify th R.java it says error so I have to restore. But After the problem when I modify R.java it says no Error, I was able to save the change. Does my R.java not generate? I do the reserach but I cant fix the problem. Everybody said the manifest, but I dont know what to change. What happned? How to fix this?

Disabling onclickListener for a memory matching game for android

I am trying to make a memory match game for android. I have the game working but with one bug. When the user taps the second button, the game uses a handler to a pause for 1 seconds to allow user to see the match and then resets the buttons, to try again. But within that 1 second pause the user is able to click another button and this screws up the game logic creating problems in the detection. I want to be able to disable onclicklistener for all buttons. I am trying to do this by using a boolean check, but it is not seeming to work. Please help, I am still a beginner with android. Thanks!!
secondScreen.java:
package eagle.abhishekravi.abhishek.eagle;
import android.app.Activity;
import java.util.*;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import android.os.Handler;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import java.util.logging.LogRecord;
import static android.app.PendingIntent.getActivity;
public class secondScreen extends Activity implements View.OnClickListener {
//drawables
int res[] = new int[] {R.drawable.brownbars,R.drawable.centeredorangedot, R.drawable.dots, R.drawable.greenlines, R.drawable.lightbulb, R.drawable.orangedots, R.drawable.orangelines, R.drawable.tree, R.drawable.yellow, R.drawable.yellowwithred, R.drawable.brownbars,R.drawable.centeredorangedot,
R.drawable.dots, R.drawable.greenlines, R.drawable.lightbulb, R.drawable.orangedots, R.drawable.orangelines, R.drawable.tree, R.drawable.yellow, R.drawable.yellowwithred};
int lay1, lay2, shuffleCount = 0, gameCount = 0;
ImageButton first, second;
LinearLayout layout;
boolean isClickable = true;
ImageButton b1;
ImageButton b2;
ImageButton b3;
ImageButton b4;
ImageButton b5;
ImageButton b6;
ImageButton b7;
ImageButton b8;
ImageButton b9;
ImageButton b10;
ImageButton b11;
ImageButton b12;
ImageButton b13;
ImageButton b14;
ImageButton b15;
ImageButton b16;
ImageButton b17;
ImageButton b18;
ImageButton b19;
ImageButton b20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Intent activityThatCalled = getIntent();
layout = new LinearLayout(this);
//initialize all buttons in game
b1 = (ImageButton) findViewById(R.id.b1);
b2 = (ImageButton) findViewById(R.id.b2);
b3 = (ImageButton) findViewById(R.id.b3);
b4 = (ImageButton) findViewById(R.id.b4);
b5 = (ImageButton) findViewById(R.id.b5);
b6 = (ImageButton) findViewById(R.id.b6);
b7 = (ImageButton) findViewById(R.id.b7);
b8 = (ImageButton) findViewById(R.id.b8);
b9 = (ImageButton) findViewById(R.id.b9);
b10 = (ImageButton) findViewById(R.id.b10);
b11 = (ImageButton) findViewById(R.id.b11);
b12 = (ImageButton) findViewById(R.id.b12);
b13 = (ImageButton) findViewById(R.id.b13);
b14 = (ImageButton) findViewById(R.id.b14);
b15 = (ImageButton) findViewById(R.id.b15);
b16 = (ImageButton) findViewById(R.id.b16);
b17 = (ImageButton) findViewById(R.id.b17);
b18 = (ImageButton) findViewById(R.id.b18);
b19 = (ImageButton) findViewById(R.id.b19);
b20 = (ImageButton) findViewById(R.id.b20);
iconRandomizer();
};
public void randomCheck(ImageButton btn, int image) {
if (gameCount < 2) {
gameCount++;
if (gameCount == 1) {
first = btn;
lay1 = image;
}
else {
System.out.println(gameCount);
isClickable = false;
second = btn;
lay2 = image;
if (lay1 != lay2) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
buttonEnabler(false);
first.setImageResource(R.color.material_blue_grey_800);
second.setImageResource(R.color.material_blue_grey_800);
first.setEnabled(true);
second.setEnabled(true);
}
}, 1000);
}
gameCount = 0;
// isClickable = true;
}
}
isClickable = true;
}
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void iconRandomizer() {
for (int i = 0; i < 10; i++)
System.out.println(res[i]);
shuffleArray(res);
for (int i = 0; i < 10; i++)
System.out.println(res[i]);
if (isClickable) {
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b10.setOnClickListener(this);
b11.setOnClickListener(this);
b12.setOnClickListener(this);
b13.setOnClickListener(this);
b14.setOnClickListener(this);
b15.setOnClickListener(this);
b16.setOnClickListener(this);
b17.setOnClickListener(this);
b18.setOnClickListener(this);
b19.setOnClickListener(this);
b20.setOnClickListener(this);
isClickable = true;
}
}
public void onClick(View v){
System.out.println(isClickable);
if (isClickable) {
switch (v.getId()) {
case R.id.b1:
if (isClickable) {
Log.d("mytag", "isclickable is true");
b1.setImageResource(res[0]);
b1.setEnabled(false);
randomCheck(b1, res[0]);
}
break;
case R.id.b2:
if (isClickable) {
b2.setImageResource(res[1]);
b2.setEnabled(false);
randomCheck(b2, res[1]);
}
break;
case R.id.b3:
b3.setImageResource(res[2]);
b3.setEnabled(false);
randomCheck(b3, res[2]);
break;
case R.id.b4:
b4.setImageResource(res[3]);
b4.setEnabled(false);
randomCheck(b4, res[3]);
break;
case R.id.b5:
b5.setImageResource(res[4]);
b5.setEnabled(false);
randomCheck(b5, res[4]);
break;
case R.id.b6:
b6.setImageResource(res[5]);
b6.setEnabled(false);
randomCheck(b6, res[5]);
break;
case R.id.b7:
b7.setImageResource(res[6]);
b7.setEnabled(false);
randomCheck(b7, res[6]);
break;
case R.id.b8:
b8.setImageResource(res[7]);
b8.setEnabled(false);
randomCheck(b8, res[7]);
break;
case R.id.b9:
b9.setImageResource(res[8]);
b9.setEnabled(false);
randomCheck(b9, res[8]);
break;
case R.id.b10:
b10.setImageResource(res[9]);
b10.setEnabled(false);
randomCheck(b10, res[9]);
break;
case R.id.b11:
b11.setImageResource(res[10]);
b11.setEnabled(false);
randomCheck(b11, res[10]);
break;
case R.id.b12:
b12.setImageResource(res[11]);
b12.setEnabled(false);
randomCheck(b12, res[11]);
case R.id.b13:
b13.setImageResource(res[12]);
b13.setEnabled(false);
randomCheck(b13, res[12]);
break;
case R.id.b14:
b14.setImageResource(res[13]);
b14.setEnabled(false);
randomCheck(b14, res[13]);
case R.id.b15:
b15.setImageResource(res[14]);
b15.setEnabled(false);
randomCheck(b15, res[14]);
break;
case R.id.b16:
b16.setImageResource(res[15]);
b16.setEnabled(false);
randomCheck(b16, res[15]);
break;
case R.id.b17:
b17.setImageResource(res[16]);
b17.setEnabled(false);
randomCheck(b17, res[16]);
break;
case R.id.b18:
b18.setImageResource(res[17]);
b18.setEnabled(false);
randomCheck(b18, res[17]);
break;
case R.id.b19:
b19.setImageResource(res[18]);
b19.setEnabled(false);
randomCheck(b19, res[18]);
break;
case R.id.b20:
b20.setImageResource(res[19]);
b20.setEnabled(false);
randomCheck(b20, res[19]);
break;
}
}
}
}
layout.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b1"
android:layout_width="90dp"
android:layout_height="90dp"
/>
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b2"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b3"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b4"
android:layout_width="90dp"
android:layout_height="90dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="2dp"
android:paddingBottom="10dp"
>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b5"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b6"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b7"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b8"
android:layout_width="90dp"
android:layout_height="90dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b9"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b10"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b11"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b12"
android:layout_width="90dp"
android:layout_height="90dp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingBottom="10dp"
>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b13"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b14"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b15"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b16"
android:layout_width="90dp"
android:layout_height="90dp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:paddingBottom="10dp"
>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b17"
android:layout_width="90dp"
android:layout_height="90dp"
/>
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b18"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b19"
android:layout_width="90dp"
android:layout_height="90dp" />
<ImageButton
android:background="#color/material_blue_grey_800"
android:id="#+id/b20"
android:layout_width="90dp"
android:layout_height="90dp" />
</LinearLayout>
</LinearLayout>

Android digital clock textview timepicker using buttons

I'm newbie Java programmer and newbie Android app developer... and i'm trying to make a simple 24h digital clock acting like a timepicker. I don't want to use the standard TimePicker widget in this case. App should work on Android 2.1+ also.
My clock i supposed look like this 23:59. When the user clicks on the clock rightmost field, buttons ranging from 0 to 9 (placed in the same Fragment) should update this rightmost field. The field should also be highlighted. I accomplished this with
view.setBackgroundResource(R.color.solid_grey);
Other fields should be updated in the same way, with some logic to avoid invalid values of course. Highlighting should be removed from first touched field when user touch another field.
My crappy solution to the problem:
What i did was to make five TextViews, one for each number and one for the colon. I have attached onTouch listeners to the changeable fields in the clock and onClick listeners for the buttons. Then i have some more or less complicated code with viewholders and tagging buttons with viewholder and what not to get all of this to work.
There MUST be a better way to do this! Don't you think?
First i tried to have a single TextView and just check which index in the string representing the clock in the textview, that was clicked. But this didn't work very good with highlighting. The index was also hard to compute with precision since i could not come up with a better idea than to use
(int) event.getX();
inside the OnTouchListener for the clock TextView.
Any ideas on how to accomplish this in the simplest possible way? If not, i have to stick with the butt-ugly hard to maintain code i made (no i won't post it here). :S
Ok, i'll post my own bulky solution here. It might not be pretty but it is working. Feel free to modify it to your liking. Keep in mind that I'm a newbie from Sweden. :P
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- The two most significant hex sets the transparency value -->
<color name="timefield_highlight_color">#FF8F8F8F</color>
<color name="timefield_no_highlight_color">#FF000000</color>
</resources>
timepicker_digital_24h.xml
Change the #dimen-stuff to your liking. Include this in your layout, using xml include-tag, wherever you want. DON'T change the id:s of the views.
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RelativeLayout
android:id="#+id/layout_timepicker_digital_24h"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/vertical_margin" >
<TextView
android:id="#+id/textview_time_set_colon_divider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_hour_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/textview_time_set_colon_divider"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_hour_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/textview_time_set_hour_right"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_minute_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/textview_time_set_colon_divider"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
<TextView
android:id="#+id/textview_time_set_minute_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/textview_time_set_minute_left"
android:maxLength="1"
android:singleLine="true"
android:text=""
android:textSize="#dimen/alarm_time_huge_textsize"
tools:ignore="SpUsage" />
</RelativeLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_1_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="1"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_2_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="2"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_3_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="3"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_4_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="4"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_5_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="5"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_6_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="6"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<LinearLayout
android:id="#+id/layout_time_buttons_row_3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/horizontal_margin_small"
android:layout_marginRight="#dimen/horizontal_margin_small" >
<Button
android:id="#+id/button_7_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="7"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_8_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="8"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
<Button
android:id="#+id/button_9_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_margin="#dimen/button_set_time_margin"
android:layout_weight="1"
android:text="9"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</LinearLayout>
<Button
android:id="#+id/button_0_time_set"
style="?android:attr/buttonStyleSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/vertical_margin_large"
android:layout_marginLeft="#dimen/horizontal_margin"
android:layout_marginRight="#dimen/horizontal_margin"
android:layout_marginTop="#dimen/button_set_time_margin"
android:text="0"
android:textSize="#dimen/button_set_time_textsize"
tools:ignore="HardcodedText" />
</merge>
Enums.java
package com.example.example.timepicker;
public class Enums {
public static enum TimeField {
HOUR_LEFT, HOUR_RIGHT, MINUTE_LEFT, MINUTE_RIGHT, NONE;
public TimeField nextReal() {
TimeField fields[] = TimeField.values();
int ordinal = this.ordinal(); // incoming field index
switch(ordinal) {
case 0: // HOUR_LEFT
ordinal = 1;
break;
case 1: // HOUR_RIGHT
ordinal = 2;
break;
case 2: // MINUTE_LEFT
ordinal = 3;
break;
case 3: // MINUTE_RIGHT
ordinal = 0;
break;
case 4: // NONE
ordinal = 0;
}
return fields[ordinal];
}
}
}
TimePickerDigital24h.java
(There is a toast-string in this code that you have to define in your strings.xml.)
package com.example.example.timepicker;
import android.app.Activity;
import android.content.Context;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.example.R;
import com.example.example.timepicker.Enums.TimeField;
public class TimePickerDigital24h implements OnClickListener, OnTouchListener {
private TimeField mTimeFieldToSet = TimeField.HOUR_LEFT;
private TextView mTextViewHourLeft, mTextViewHourRight, mTextViewMinuteLeft, mTextViewMinuteRight;
private Context mContext;
public TimePickerDigital24h (Context context, String hourOfDay, String minute) {
mContext = context;
mTextViewHourLeft = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_hour_left);
mTextViewHourLeft.setText(hourOfDay.substring(0, 1));
mTextViewHourRight = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_hour_right);
mTextViewHourRight.setText(hourOfDay.substring(1, 2));
mTextViewMinuteLeft = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_minute_left);
mTextViewMinuteLeft.setText(minute.substring(0, 1));
mTextViewMinuteRight = (TextView) ((Activity) context).findViewById(R.id.textview_time_set_minute_right);
mTextViewMinuteRight.setText(minute.substring(1, 2));
mTextViewHourLeft.setOnTouchListener(this);
mTextViewHourRight.setOnTouchListener(this);
mTextViewMinuteLeft.setOnTouchListener(this);
mTextViewMinuteRight.setOnTouchListener(this);
this.setTimeFieldHighlight(TimeField.HOUR_LEFT);
Button button0 = (Button) ((Activity) context).findViewById(R.id.button_0_time_set);
button0.setOnClickListener(this);
Button button1 = (Button) ((Activity) context).findViewById(R.id.button_1_time_set);
button1.setOnClickListener(this);
Button button2 = (Button) ((Activity) context).findViewById(R.id.button_2_time_set);
button2.setOnClickListener(this);
Button button3 = (Button) ((Activity) context).findViewById(R.id.button_3_time_set);
button3.setOnClickListener(this);
Button button4 = (Button) ((Activity) context).findViewById(R.id.button_4_time_set);
button4.setOnClickListener(this);
Button button5 = (Button) ((Activity) context).findViewById(R.id.button_5_time_set);
button5.setOnClickListener(this);
Button button6 = (Button) ((Activity) context).findViewById(R.id.button_6_time_set);
button6.setOnClickListener(this);
Button button7 = (Button) ((Activity) context).findViewById(R.id.button_7_time_set);
button7.setOnClickListener(this);
Button button8 = (Button) ((Activity) context).findViewById(R.id.button_8_time_set);
button8.setOnClickListener(this);
Button button9 = (Button) ((Activity) context).findViewById(R.id.button_9_time_set);
button9.setOnClickListener(this);
}
#Override
public boolean onTouch(View view, MotionEvent event) {
switch(view.getId()) {
case R.id.textview_time_set_hour_left:
mTimeFieldToSet = TimeField.HOUR_LEFT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_hour_right:
mTimeFieldToSet = TimeField.HOUR_RIGHT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_minute_left:
mTimeFieldToSet = TimeField.MINUTE_LEFT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
case R.id.textview_time_set_minute_right:
mTimeFieldToSet = TimeField.MINUTE_RIGHT;
this.setTimeFieldHighlight(mTimeFieldToSet);
return true;
}
return false;
}
#Override
public void onClick(View view) {
int valueToSet = 0;
switch(view.getId()) {
case R.id.button_0_time_set:
valueToSet = 0;
break;
case R.id.button_1_time_set:
valueToSet = 1;
break;
case R.id.button_2_time_set:
valueToSet = 2;
break;
case R.id.button_3_time_set:
valueToSet = 3;
break;
case R.id.button_4_time_set:
valueToSet = 4;
break;
case R.id.button_5_time_set:
valueToSet = 5;
break;
case R.id.button_6_time_set:
valueToSet = 6;
break;
case R.id.button_7_time_set:
valueToSet = 7;
break;
case R.id.button_8_time_set:
valueToSet = 8;
break;
case R.id.button_9_time_set:
valueToSet = 9;
break;
}
try {
this.setTimeField(valueToSet);
} catch (UnsupportedOperationException e) {
Toast.makeText(mContext, mContext.getString(R.string.toast_time_set_error), Toast.LENGTH_LONG).show();
//e.printStackTrace();
}
}
// Setter for timefields in the clock time display. Also highlights the correct field.
private void setTimeField (int valueToSet) throws UnsupportedOperationException {
int hourLeft = Integer.parseInt(mTextViewHourLeft.getText().toString());
int hourRight = Integer.parseInt(mTextViewHourRight.getText().toString());
UnsupportedOperationException exception = new UnsupportedOperationException("Input value invalid for this clock field");
setTimeFieldHighlight(mTimeFieldToSet.nextReal());
switch(mTimeFieldToSet) {
case HOUR_LEFT:
if (valueToSet <= 1) {
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else if (valueToSet <= 2 && hourRight <= 3) {
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else if (valueToSet <= 2 && hourRight >= 4) {
mTextViewHourRight.setText("3");
mTextViewHourLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_RIGHT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case HOUR_RIGHT:
if (valueToSet <= 3) {
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else if (valueToSet > 3 && hourLeft <= 1) {
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else if (valueToSet > 3 && hourLeft >= 2) {
mTextViewHourLeft.setText("1");
mTextViewHourRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_LEFT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case MINUTE_LEFT:
if (valueToSet <= 5) {
mTextViewMinuteLeft.setText("" + valueToSet);
mTimeFieldToSet = TimeField.MINUTE_RIGHT;
break;
} else {
setTimeFieldHighlight(mTimeFieldToSet);
throw exception;
}
case MINUTE_RIGHT:
mTextViewMinuteRight.setText("" + valueToSet);
mTimeFieldToSet = TimeField.HOUR_LEFT;
break;
case NONE:
}
}
// Highlighting of the fields in the clock display
private void setTimeFieldHighlight(TimeField field) {
switch(field) {
case HOUR_LEFT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case HOUR_RIGHT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case MINUTE_LEFT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
break;
case MINUTE_RIGHT:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_highlight_color);
break;
case NONE:
mTextViewHourLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewHourRight.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteLeft.setBackgroundResource(R.color.timefield_no_highlight_color);
mTextViewMinuteRight.setBackgroundResource(R.color.timefield_no_highlight_color);
}
}
public String getHourOfDay() {
String hourOfDay = mTextViewHourLeft.getText().toString()
+ mTextViewHourRight.getText().toString();
return hourOfDay;
}
public String getMinute() {
String minute = mTextViewMinuteLeft.getText().toString()
+ mTextViewMinuteRight.getText().toString();
return minute;
}
}
**Put this code in your Fragment's OnActivityCreated method to instantiate the TimePickerDigital24h object: **
mTimePicker = new TimePickerDigital24h(getActivity(), "23", "59");
You can read back the time set by the user this way:
mTimePicker.getHourOfDay();
mTimePicker.getMinute();
I'm sure the code could be better in many ways. If you guys know how to do this in a much simpler way, please let me know. / TiredDude

Handling RadioGroup and Button Events in Android

I am a beginner in Android and I am trying to create a simple Android app
which has two Text boxes (EditText) to take two Numbers as Input. Then I am Creating Radio Group having four Radio Buttons (Add,Sub,Multiply,Divide).
Then I am having a Button to get the results. I am getting an AlertBox saying "Unfortunately, SimpleApp has stopped working" the moment I click the Button. Kindly assist me.
*Here is my Java code *
package com.example.simpleapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
private EditText txt1;
private EditText txt2;
private String input1;
private String input2;
private Double Num1;
private Double Num2;
private String flag;
private EditText TextResult;
Double Result=0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initControls();
}
private void initControls()
{
((Button)findViewById(R.id.button1)).setOnClickListener(this);
}
public void onradioButtonClicked(View view)
{
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId())
{
case R.id.radio0:
if(checked)
flag = "add";
//Result = Num1+Num2;
break;
case R.id.radio1:
if(checked)
flag = "sub";
//Result = Num1-Num2;
break;
case R.id.radio2:
if(checked)
flag = "prod";
//Result = Num1*Num2;
break;
case R.id.radio3:
if(checked)
flag = "div";
//Result = Num1/Num2;
break;
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
TextResult = (EditText)findViewById(R.id.textView2);
TextResult.setText("0");
txt1 = (EditText)findViewById(R.id.editText1);
txt2 = (EditText)findViewById(R.id.editText2);
input1 = txt1.getText().toString();
input2 = txt2.getText().toString();
Num1 = Double.parseDouble(input1);
Num2 = Double.parseDouble(input2);
if(flag == "add")
Result = Num1+Num2;
else if(flag == "sub")
Result = Num1-Num2;
else if(flag == "prod")
Result = Num1*Num2;
else Result = Num1/Num2;
TextResult.setText(String.valueOf(Result));
}
}
Here is my Activity_Main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="102dp"
android:layout_marginTop="66dp"
android:orientation="vertical" >
</LinearLayout>
<TableRow
android:id="#+id/tableRow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_below="#+id/linearLayout1"
android:layout_marginTop="34dp" >
</TableRow>
<TableRow
android:id="#+id/tableRow2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableRow1"
android:layout_below="#+id/tableRow1"
android:layout_marginLeft="14dp" >
</TableRow>
<EditText
android:id="#+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tableRow1"
android:layout_alignTop="#+id/tableRow2"
android:ems="10"
android:hint="Enter Second Number"
android:inputType="number" />
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter First Number"
android:inputType="number" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText1"
android:layout_alignParentTop="true"
android:layout_marginTop="14dp"
android:text="Simple Calculator App"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TableRow
android:id="#+id/tableRow3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/editText2"
android:layout_below="#+id/editText2"
android:layout_marginTop="36dp" >
</TableRow>
<RadioGroup
android:id="#+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_below="#+id/editText2" >
<RadioButton
android:id="#+id/radio0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Add"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Sub"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply"
android:onClick="onradioButtonClicked"/>
<RadioButton
android:id="#+id/radio3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Divide"
android:onClick="onradioButtonClicked"/>
</RadioGroup>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_below="#+id/radioGroup1"
android:text="Check"
/>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
Your if then statements have wrong syntax. Try this:
if(flag == "add"){
Result = Num1+Num2;
}else if(flag == "sub"){
Result = Num1-Num2;
}else if(flag == "prod"){
Result = Num1*Num2;
}else{
Result = Num1/Num2;
}
try this ... calculation on click as well as on radio button checked change
public class MainActivity extends Activity implements OnClickListener,
OnCheckedChangeListener {
private EditText txt1;
private EditText txt2;
// private String input1;
// private String input2;
private Double Num1;
private Double Num2;
// private String flag;
private TextView TextResult;
Double Result = 0.0;
RadioButton radio0, radio1, radio2, radio3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
findViewById(R.id.button1).setOnClickListener(this);
radio0 = (RadioButton) findViewById(R.id.radio0);
radio0.setOnCheckedChangeListener(this);
radio1 = (RadioButton) findViewById(R.id.radio1);
radio1.setOnCheckedChangeListener(this);
radio2 = (RadioButton) findViewById(R.id.radio2);
radio2.setOnCheckedChangeListener(this);
radio3 = (RadioButton) findViewById(R.id.radio3);
radio3.setOnCheckedChangeListener(this);
TextResult = (TextView) findViewById(R.id.textView2);
TextResult.setText("0");
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
}
public void onradioButtonClicked(View view) {
}
#Override
public void onClick(View v) {
getCalculationValue();
// input1 = txt1.getText().toString();
// input2 = txt2.getText().toString();
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getCalculationValue();
}
private void getCalculationValue() {
Num1 = Double.parseDouble(txt1.getText().toString().trim());
Num2 = Double.parseDouble(txt2.getText().toString().trim());
if (radio0.isChecked())
Result = Num1 + Num2;
else if (radio1.isChecked())
Result = Num1 - Num2;
else if (radio2.isChecked())
Result = Num1 * Num2;
else if (radio3.isChecked())
Result = Num1 / Num2;
TextResult.setText(String.valueOf(Result));
}
}
You are Typecasted TextView into EditText.
So Android rises ClassCastException
08-03 17:08:30.415: E/AndroidRuntime(7702): java.lang.ClassCastException: android.widget.TextView
private EditText TextResult;
TextResult = (EditText)findViewById(R.id.textView2);
Change these lines into
private TextView TextResult;
TextResult = (TextView) findViewById(R.id.textView2);

Categories

Resources