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.
Related
Why when I click the button and nothing is written in EditText, the program crashes?
The app is used to calculate the load securing.Users enter values and get the number of straps they need.But when a field is free, the app crashes
Code:
public class Ladungssicherung extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
EditText stfinput;
EditText gewichtinput;
EditText winkelinput;
String text;
double k = 1.5;
int cZ = 1; // beschleunigungsbeiwert nach unten
double cX = 0.8; // beschleunigungsbeiwert nach vorne
Dialog epicDialog;
TextView unicode, ergebnissFeld;
ImageView muinfoButton, closemuButton, infoalphaButton;
#SuppressLint("StringFormatInvalid")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_ladungssicherung);
winkelinput = (EditText) findViewById(R.id.winkelInput);
ergebnissFeld = (TextView) findViewById(R.id.ergebniss);
gewichtinput = (EditText) findViewById(R.id.gewichtInput);
stfinput = (EditText) findViewById(R.id.stfInput);
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
text = sharedPreferences.getString("text", "");
winkelinput.setText(text);
sharedPreferences.edit().remove("text").commit();
epicDialog = new Dialog(this, android.R.style.Theme_DeviceDefault_Light_NoActionBar_Fullscreen);
muinfoButton = (ImageView) findViewById(R.id.infomuIcon);
closemuButton = (ImageView) findViewById(R.id.closemuinfo);
infoalphaButton = (ImageView) findViewById(R.id.infoalpha);
muinfoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showmuinfo();
}
});
infoalphaButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showalphawinkel();
}
});
//Spinner code
Spinner spinner = findViewById(R.id.spinner1);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.numbers, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
}
public void showalphawinkel() {
Intent intent = new Intent(this, WinkelmessActivity.class);
startActivity(intent);
}
public void showmuinfo() {
epicDialog.setContentView(R.layout.muinfo);
closemuButton = (ImageView) epicDialog.findViewById(R.id.closemuinfo);
closemuButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
epicDialog.dismiss();
}
});
epicDialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
epicDialog.show();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void ergebnissFromel(View v) {
Spinner feld4 = (Spinner) findViewById(R.id.spinner1);
Integer zahl1 = Integer.parseInt(gewichtinput.getText().toString());
Integer zahl2 = Integer.parseInt(winkelinput.getText().toString());
Integer zahl3 = Integer.parseInt(stfinput.getText().toString());
String spinner = feld4.getSelectedItem().toString();
xml layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Ladungssicherung">
<ImageView
android:id="#+id/infoalpha"
android:layout_width="38dp"
android:layout_height="40dp"
android:layout_alignBottom="#+id/winkelInput"
android:layout_alignStart="#+id/infomuIcon"
app:srcCompat="#drawable/info_icon" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="97dp"
android:layout_height="34dp"
android:layout_alignParentBottom="true"
android:layout_marginBottom="223dp"
android:layout_toEndOf="#+id/textView">
</Spinner>
<TextView
android:id="#+id/textView"
android:layout_width="117dp"
android:layout_height="29dp"
android:layout_above="#+id/gewichtInput"
android:layout_alignStart="#+id/gewichtInput"
android:layout_marginBottom="-108dp"
android:text="Gewicht"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/gewichtInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="108dp"
android:ems="10"
android:hint="kg"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/winkelInput"
android:layout_marginBottom="-211dp"
android:layout_toStartOf="#+id/spinner1"
android:text="Winkel Alpha"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/winkelInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="211dp"
android:ems="10"
android:hint="#string/alpha"
android:inputType="textPersonName" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/stfInput"
android:layout_alignStart="#+id/textView"
android:text="Vorspannkraft je Gurt"
android:textSize="20sp"
android:textStyle="bold|italic" />
<EditText
android:id="#+id/stfInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/textView5"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="daN"
android:inputType="textPersonName" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="37dp"
android:layout_height="29dp"
android:layout_alignParentTop="true"
android:layout_alignStart="#+id/textView5"
android:layout_marginTop="116dp"
app:srcCompat="#drawable/gewicht" />
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="175dp"
android:background="#color/grau">
</View>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="277dp"
android:background="#color/grau">
</View>
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="275dp"
android:background="#color/grau">
</View>
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/spinner1"
android:layout_marginStart="46dp"
android:text="#string/mue"
android:textSize="25sp" />
<TextView
android:id="#+id/textView5"
android:layout_width="15dp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginEnd="-3dp"
android:layout_toStartOf="#+id/textView6"
android:text="S"
android:textSize="23sp" />
<TextView
android:id="#+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/stfInput"
android:layout_marginStart="3dp"
android:layout_alignStart="#+id/textView4"
android:text="TF"
android:textSize="23sp" />
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/winkelInput"
android:layout_alignStart="#+id/textView4"
android:text="#string/alpha"
android:textSize="23sp" />
<ImageView
android:id="#+id/infomuIcon"
android:layout_width="38dp"
android:layout_height="40dp"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/spinner1"
android:layout_marginTop="-2dp"
android:layout_marginEnd="17dp"
app:srcCompat="#drawable/info_icon" />
<TextView
android:id="#+id/titelNiederzurren"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="21dp"
android:textSize="20sp"
android:textColor="#color/blue"
android:text="Niederzurren" />
<View
android:layout_width="wrap_content"
android:layout_height="2dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="199dp"
android:background="#color/grau">
</View>
<TextView
android:id="#+id/ergebniss"
android:layout_width="154dp"
android:layout_height="36dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="53dp"
android:background="#color/greensmiley"
android:text="" />
<Button
android:id="#+id/buttonladungssicherung"
android:layout_width="144dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="120dp"
android:text="Button"
android:onClick="ergebnissFromel"
/>
</RelativeLayout>
You are probably getting NumberFormatException because you are trying to parse empty String to Integer. Surround Integer.parseInt(gewichtinput.getText().toString()) lines with try catch blocks, and it should be fine.
Try these codes and let us get updated with what you see:
public void ergebnissFromel(View v) {
Spinner feld4 = (Spinner) findViewById(R.id.spinner1);
Integer zahl1 = 0;
Integer zahl2 = 0;
Integer zahl3 = 0;
try
{
zahl1 = Integer.parseInt(gewichtinput.getText().toString());
zahl2 = Integer.parseInt(winkelinput.getText().toString());
zahl3 = Integer.parseInt(stfinput.getText().toString());
} catch (Exception e) {
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
return;
}
String spinner = feld4.getSelectedItem().toString();
if ( zahl1.equals("") || zahl1 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
if ( zahl2.equals("") || zahl2 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
if ( zahl3.equals("") || zahl3 == null){
Toast.makeText(this, "Bitte geben Sie das Gewicht an", Toast.LENGTH_SHORT).show();
}
else {
// Grad wird in sinus alpha umgerechnet
double newsinus = Math.sin(Math.toRadians(Float.valueOf(zahl2)));
double wert1 = cX - Float.valueOf(spinner) * cZ;
double wert2 = Float.valueOf(spinner) * newsinus;
// Formel Niederzurren Algorithmus
double wert3 = wert1 * zahl1;
double wert4 = wert2 * k;
double wert5 = wert3 / wert4;
double wert6 = Math.round(wert5);
double wert7 = wert6 / zahl3;
double wert8 = Math.ceil(wert7);
ergebnissFeld.setText(String.valueOf(Math.round(wert8)));
}
}
Usually when your app crashes, you'll find a stack trace logged that will help you understand where the problem is. You can find the log within Android Studio's Debug|Console tab. Alternatively you can use the adb command from a terminal/shell window. I like using "adb logcat -v time".
Before parsing to integer, you should check wether the input is null.
Furthermore, you're calling a method on zahl1 and check wether it is null afterwards.
String strZahl1 = gewichtinput.getText().toString(); //Get input as String
if(strZahl1 == null || strZahl1.isEmpty()) //First make sure that strZahl1 is not null, then check wether it is empty
{
Toast.makeText(this, "Bitte geben Sie das Gewicht an",Toast.LENGTH_SHORT).show();
}
Integer zahl1 = Integer.parseInt(strZahl1);
If the user is able to enter something else than a number into your textfields, you could surround the parsing with a try block:
Integer zahl1;
try
{
zahl1 = Integer.parseInt(strZahl1);
}
catch(NumberFormatException e)
{
Toast.makeText(this, strZahl1 + " ist keine gültige Zahl", Toast.LENGTH_SHORT).show();
}
Your app crashes because .getText().toString is an empty string. Java cannot convert an empty string into an integer.
A better way is to do something like
Integer zahl1 ;
if((gewichtinput.getText() != null) && (!gewichtinput.getText().toString.isEmpty()))
{
zahl1 = Integer.parseInt(gewichtinput.getText().toString());
}
else
{
zahl1 = 0 ;
}
Do the same for all the other edit texts.
It should hopefully work
I'm making an android app for a simple calculator. The most important part is that it uses a "rolling" textView, so for example if you did 1+1, then if you pressed another arithmetic operator, "+" for example, the textView would then turn into 2+(enter new number, 3 for example) and then if you clicked multiply, it would then show 5* etc etc.
Right now the error is at line34 showing a null pointer error when I click the number 1 on the calculator. Wondering if anybody can assist me on this / other logic errors if you see them.
Basically if you click to use an arithmetic operator on the calculator, and if there's already an operator in the textView on the calculator, then it calculates the current textView and spits that new arithmetic operator beside it. Otherwise if there are no arithmetic operators on the calculator, it just puts the operator beside the first number.
What I'm trying to do is:
if the user clicks a number, then set rollingBar to that number
if the user clicks an operator
if it is the first operator then there must be only 1 string inside of
the rollingBar, so assign that string to leftNum, and assign the first
operator type to the text of the button eg. "1".
get text in rolling bar, assign it to text1, make text2 and assign
it to text1 + stringButton(which would be 1,2,3,4 etc.. name of btn.
set the first operator to false
if it's not the first operator, then you need to calculate by splitting
the function at the first arithmetic operator, assign the last number
from the split into rightNum
switch to the first operator type
do the math
assign this second operator to the next rollingBar
Right now I'm getting some problems... I'll show a picture and the java file...
Picture:
http://imgur.com/35hy4Ze
Java File:
package com.example.w0273754.calcfinal;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.lang.String;
public class MainActivity extends AppCompatActivity {
//declarations
TextView rollingBar;//where all of the text goes when the user clicks a button
String leftNum;
String rightNum;
boolean firstOptr;
String firstOptrType;
String number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollingBar = (TextView) findViewById(R.id.rollingBar);
leftNum = "";
rightNum = "";
firstOptr = true;
number = "";
}
public void number(View v){
Button button = (Button) v;
number += button.getText().toString();
rollingBar.setText(number);
}
//i can click 1 and it outputs 1
// i can click + and it outputs +
// when I click next number it just outputs the number, nothing else
public void operater(View v) {
Button button = (Button) v;
String stringButton = button.getText().toString();
//if it's the first operator being done, then set the rollbar text to text1,
// then add the operator string to text1 and store it in text 2.
if (firstOptr) {
leftNum = rollingBar.getText().toString();
firstOptrType = stringButton;
number += stringButton;
rollingBar.setText(number);
firstOptr = false;
}
//if it's not the first operator, then you need to calculate leftnum and the right num
else {
String fullString = (String) rollingBar.getText().toString();
String[] bits = fullString.split("[-+*/]");
rightNum = bits[bits.length - 1];
switch (firstOptrType) {
case "+":
add(leftNum, rightNum);
break;
case "-":
break;
case "*":
break;
case "/":
break;
default:
rollingBar.setText("OPERATOR METHOD PROBLEM");
}
}
}
public void add(String leftNum, String rightNum){
int parsedLeftNum = Integer.parseInt(leftNum);
int parsedRightNum = Integer.parseInt(rightNum);
rollingBar.setText(parsedLeftNum + parsedRightNum);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
XML file:
<TableLayout android:id="#+id/TableLayout"
tools:context=".MainActivity"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android">
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/rollingBar" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="1" android:layout_span="4" android:text="#string/rollingBar"/>
</TableRow>
<TableRow android:layout_height="match_parent"
android:layout_width="match_parent">
<Button android:id="#+id/buttonClear" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/buttonClear" />
<Button android:id="#+id/buttonPlusMinus" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonPlusMinus" android:onClick="onClick1"/>
<Button android:id="#+id/buttonDelete" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonDelete" />
<Button android:id="#+id/buttonDivide" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonDivide" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button7" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button7" android:onClick="number" android:nestedScrollingEnabled="false"/>
<Button android:id="#+id/button8" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button8" android:onClick="number"/>
<Button android:id="#+id/button9" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button9" android:onClick="number"/>
<Button android:id="#+id/buttonMultiply" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonMultiply" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button4" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button4" android:onClick="number"/>
<Button android:id="#+id/button5" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button5" android:onClick="number"/>
<Button android:id="#+id/button6" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="#string/button6" android:onClick="number"/>
<Button android:id="#+id/buttonSubtract" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonSubtract" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="wrap_content" android:layout_width="match_parent">
<Button android:id="#+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button1" android:onClick="number"/>
<Button android:id="#+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button2" android:onClick="number"/>
<Button android:id="#+id/button3" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/button3" android:onClick="number"/>
<Button android:id="#+id/buttonAdd" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_column="3" android:text="#string/buttonAdd" android:onClick="operater"/>
</TableRow>
<TableRow android:paddingBottom="10dp" android:layout_height="match_parent" android:layout_width="match_parent">
<Button android:id="#+id/button0" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="2" android:text="#string/button0" android:onClick="number"/>
<Button android:id="#+id/buttonDecimal" android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonDecimal"/>
<Button android:id="#+id/buttonEqual" android:layout_height="match_parent" android:layout_width="wrap_content" android:layout_span="1" android:text="#string/buttonEqual" android:onClick="operater"/>
</TableRow>
<TableRow android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/textView" android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="0"/>
</TableRow>
<TableRow android:layout_height="match_parent" android:layout_width="match_parent">
<TextView android:id="#+id/errorMessage" android:layout_height="wrap_content" android:layout_width="wrap_content"/>
</TableRow>
</TableLayout>
Thank you very much,for the help!
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView rollingBar = (TextView) findViewById(R.id.rollingBar); // <-- HERE
String leftNum = "";
String rightNum = "";
boolean firstOptr = true;
String firstOptrType;
}
You declare a local variable rollingBar in onCreate which shadow the member variable of your Activity, so the member variable rollingBar always null, delete the TextView:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rollingBar = (TextView) findViewById(R.id.rollingBar);
String leftNum = "";
String rightNum = "";
boolean firstOptr = true;
String firstOptrType;
}
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
Hi i'm working on a Android Launcher that Shows Calculator activity. It shows the layout fine but does nothing when you click on any of the buttons I need help I have tried everything I can and i'm getting upset! any help would be amazing!!
Calculator.java:
package com.dva.schooltoolshome;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Calculator extends FragmentActivity implements OnClickListener {
private TextView calculatorDisplay;
private static final String DIGITS = "0123456789.";
private Boolean userIsInTheMiddleOfTypingANumber = false;
DecimalFormat df = new DecimalFormat("############");
CalculatorBrain brain;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
brain = new CalculatorBrain();
calculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
findViewById(R.id.buttonClearMemory).setOnClickListener(this);
findViewById(R.id.buttonAddToMemory).setOnClickListener(this);
findViewById(R.id.buttonSubtractFromMemory).setOnClickListener(this);
findViewById(R.id.buttonRecallMemory).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonCos) != null) {
findViewById(R.id.buttonCos).setOnClickListener(this);
}
if (findViewById(R.id.buttonSin) != null) {
findViewById(R.id.buttonSin).setOnClickListener(this);
}
// Another way to hide the window title and actionbar, but only in newer sdk's
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// ActionBar actionBar = getActionBar();
// actionBar.setDisplayShowHomeEnabled(false);
// actionBar.setDisplayShowTitleEnabled(false);
// actionBar.hide();
// }
}
// #Override
public void onClick(View view) {
String buttonPressed = ((Button) view).getText().toString();
// String digits = "0123456789.";
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
calculatorDisplay.append(buttonPressed);
} else {
calculatorDisplay.setText(buttonPressed);
userIsInTheMiddleOfTypingANumber = true;
}
} else {
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
brain.setOperand(Double.parseDouble(calculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
brain.performOperation(buttonPressed);
calculatorDisplay.setText(df.format(brain.getResult()));
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", brain.getResult());
outState.putDouble("MEMORY", brain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
brain.setOperand(savedInstanceState.getDouble("OPERAND"));
brain.setMemory(savedInstanceState.getDouble("MEMORY"));
calculatorDisplay.setText(df.format(brain.getResult()));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
}
CalculatorBrain.java:
package com.dva.schooltoolshome;
public class CalculatorBrain {
// 3 + 6 = 9
// 3 & 6 are called the operand.
// The + is called the operator.
// 9 is the result of the operation.
private double operand = 0;
private double waitingOperand = 0;
private String waitingOperator = "";
private double calculatorMemory = 0;
public void setOperand(double operand) {
this.operand = operand;
}
public double getResult() {
return operand;
}
// used on screen orientation change
public void setMemory(double calculatorMemory) {
this.calculatorMemory = calculatorMemory;
}
// used on screen orientation change
public double getMemory() {
return calculatorMemory;
}
public String toString() {
return Double.toString(operand);
}
protected double performOperation(String operator) {
/*
* If you are using Java 7, then you can use switch in place of if statements
*
* switch (operator) {
* case "MC":
* calculatorMemory = 0;
* break;
* case "M+":
* calculatorMemory = calculatorMemory + operand;
* break;
* }
*/
if (operator.equals("MC")) {
calculatorMemory = 0;
} else if (operator.equals("M+")) {
calculatorMemory = calculatorMemory + operand;
} else if (operator.equals("M-")) {
calculatorMemory = calculatorMemory - operand;
} else if (operator.equals("MR")) {
operand = calculatorMemory;
} else if (operator.equals("C")) {
operand = 0;
waitingOperator = "";
waitingOperand = 0;
calculatorMemory = 0;
} else if (operator.equals("Sqrt")) {
operand = Math.sqrt(operand);
} else if (operator.equals("1/x")) {
if (operand != 0) {
operand = 1 / operand;
}
} else if (operator.equals("+/-")) {
operand = -operand;
} else if (operator.equals("sin")) {
operand = Math.sin(operand);
} else if (operator.equals("cos")) {
operand = Math.cos(operand);
} else {
performWaitingOperation();
waitingOperator = operator;
waitingOperand = operand;
}
return operand;
}
protected void performWaitingOperation() {
if (waitingOperator.equals("+")) {
operand = waitingOperand + operand;
} else if (waitingOperator.equals("*")) {
operand = waitingOperand * operand;
} else if (waitingOperator.equals("-")) {
operand = waitingOperand - operand;
} else if (waitingOperator.equals("/")) {
if (operand != 0) {
operand = waitingOperand / operand;
}
}
}
}
activity_calculator.xml:
<RelativeLayout xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:maxLines="1"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:text="0"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="40sp" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout1" >
<Button
android:id="#+id/buttonAddToMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M+" />
<Button
android:id="#+id/buttonSubtractFromMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="M-" />
<Button
android:id="#+id/buttonRecallMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="MR" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout2" >
<Button
android:id="#+id/buttonClear"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="C" />
<Button
android:id="#+id/buttonToggleSign"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+/-" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="/" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="*" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout3" >
<Button
android:id="#+id/button7"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button7" />
<Button
android:id="#+id/button8"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button8" />
<Button
android:id="#+id/button9"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button9" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="-" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout4" >
<Button
android:id="#+id/button4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button4" />
<Button
android:id="#+id/button5"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button5" />
<Button
android:id="#+id/button6"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="#string/button6" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".25"
android:text="+" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/linearLayout5"
android:baselineAligned="false" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".75"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout7"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button1" />
<Button
android:id="#+id/button2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".33"
android:text="#string/button2" />
<Button
android:id="#+id/button3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="#string/button3" />
</LinearLayout>
<LinearLayout
android:id="#+id/linearLayout8"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button0"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".66"
android:text="#string/button0" />
<Button
android:id="#+id/buttonDecimalPoint"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".34"
android:text="." />
</LinearLayout>
</LinearLayout>
<Button
android:id="#+id/buttonEquals"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".25"
android:text="=" />
</LinearLayout>
<ImageButton
android:id="#+id/apps"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<ImageButton
android:id="#+id/wbrowser"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:src="#drawable/browser" />
<ImageButton
android:id="#+id/ImageButton01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/wbrowser"
android:background="#drawable/appdrawer"
android:src="#drawable/appdrawer" />
<Button
android:id="#+id/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ImageButton01"
android:layout_centerHorizontal="true"
android:text="Tools" />
<Button
android:id="#+id/buttonClearMemory"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_above="#+id/ImageButton01"
android:layout_alignLeft="#+id/tools"
android:layout_marginBottom="163dp"
android:layout_weight=".25"
android:text="MC" />
</RelativeLayout>
I'm still new to android development so please don't judge
Regards
Rapsong11
First of all use switch statement in OnClick(View v) function for every button.
like this.
public void onClick(View v)
{
case R.Id.button1
// the functionality code goes here
break;
case R.id.button2
break;
}
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);