My android app keeps on crashing - java

I want to make a Scientific Calculator(Android app) but some problems appears. I don't know Java but I understand the code because I know C++.
I had modified the code of a normal Calculator into a Scientific Calculator but the code doesn't seems to work.
Only the basic functions like +,-,*,/ work but the functions which I added like Sin,Cos,Tan,Sqrt,Pow,Exp etc. doesn't seems to work when I use those functions the app crashes.
This is my source code.
MainActivity.java
package com.example.anant.scientificcalculator;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import static java.lang.Math.*;
import java.text.DecimalFormat;
import com.example.anant.scientificcalculator.databinding.MainActivityBinding;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private MainActivityBinding binding;
private static final char FACT = '!';
private static final char POWER = '^';
private static final String SQRT = "SQRT";
private static final String SIN = "SIN";
private static final String COS = "COS";
private static final String TAN = "TAN";
private static final String LOG = "LOG";
private static final char LEFTC = '(';
private static final char RIGHTC = ')';
private static final String EXP = "EXP";
private static final String PIE = "PIE";
private static final char ADD = '+';
private static final char SUBTRACT = '-';
private static final char MULTIPlY = '*';
private static final char DIVIDE = '/';
private char CURRENT_ACTION;
private String ADVANCE_ACTION;
private double valueOne = Double.NaN;
private double valueTwo;
private double valueTemp;
private DecimalFormat decimalFormat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
decimalFormat = new DecimalFormat("#.##########");
binding = DataBindingUtil.setContentView(this, R.layout.main_activity);
binding.buttonDot.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ".");
}
});
binding.buttonZero.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "0");
}
});
binding.buttonOne.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "1");
}
});
binding.buttonTwo.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "2");
}
});
binding.buttonThree.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "3");
}
});
binding.buttonFour.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "4");
}
});
binding.buttonFive.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "5");
}
});
binding.buttonSix.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "6");
}
});
binding.buttonSeven.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "7");
}
});
binding.buttonEight.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "8");
}
});
binding.buttonNine.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "9");
}
});
binding.buttonLeftC.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + "(");
}
});
binding.buttonRightC.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
binding.editText.setText(binding.editText.getText() + ")");
}
});
binding.buttonExp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = EXP;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "EXP");
binding.editText.setText(null);
}
});
binding.buttonPie.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
computeCalculation();
ADVANCE_ACTION = PIE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "PIE");
binding.editText.setText(null);
}
});
binding.buttonAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = ADD;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "+");
binding.editText.setText(null);
}
});
binding.buttonSubtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = SUBTRACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "-");
binding.editText.setText(null);
}
});
binding.buttonMultiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = MULTIPlY;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "*");
binding.editText.setText(null);
}
});
binding.buttonDivide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = DIVIDE;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "/");
binding.editText.setText(null);
}
});
binding.buttonFact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = FACT;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "!");
binding.editText.setText(null);
}
});
binding.buttonPow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
CURRENT_ACTION = POWER;
binding.infoTextView.setText(decimalFormat.format(valueOne) + "^");
binding.editText.setText(null);
}
});
binding.buttonSqrt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SQRT;
binding.infoTextView.setText("SQRT(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonSine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = SIN;
binding.infoTextView.setText("SIN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonCosine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = COS;
binding.infoTextView.setText("COS(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonTangent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = TAN;
binding.infoTextView.setText("TAN(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonLog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
ADVANCE_ACTION = LOG;
binding.infoTextView.setText("LOG(" + decimalFormat.format(valueOne) + ")");
binding.editText.setText(null);
}
});
binding.buttonEqual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
computeCalculation();
binding.infoTextView.setText(binding.infoTextView.getText().toString() +
decimalFormat.format(valueTwo) + " = " + decimalFormat.format(valueOne));
valueOne = Double.NaN;
CURRENT_ACTION = '0';
}
});
binding.buttonClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(binding.editText.getText().length() > 0) {
CharSequence currentText = binding.editText.getText();
binding.editText.setText(currentText.subSequence(0, currentText.length()-1));
}
else {
valueOne = Double.NaN;
valueTwo = Double.NaN;
binding.editText.setText("");
binding.infoTextView.setText("");
}
}
});
}
private void computeCalculation() {
if(!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
if(CURRENT_ACTION == ADD)
valueOne = this.valueOne + valueTwo;
else if(CURRENT_ACTION == SUBTRACT)
valueOne = this.valueOne - valueTwo;
else if(CURRENT_ACTION == MULTIPlY)
valueOne = this.valueOne * valueTwo;
else if(CURRENT_ACTION == DIVIDE)
valueOne = this.valueOne / valueTwo;
else if(CURRENT_ACTION == FACT)
{
valueTemp = this.valueOne;
int i,valueThree=1;
for(i=(int) valueTemp;i>0;i--) //type conversion
{
valueThree *= i;
}
valueOne = valueThree;
}
else if(CURRENT_ACTION == POWER) {
valueTemp = this.valueOne;
valueTemp = Math.pow(valueOne, valueTwo);
valueOne = valueTemp;
}
else if(ADVANCE_ACTION == SQRT) {
valueTemp = this.valueOne;
valueOne = Math.sqrt(valueTemp);
}
else if(ADVANCE_ACTION == SIN) {
valueTemp = this.valueOne;
valueOne = Math.sin(valueTemp);
}
else if(ADVANCE_ACTION == COS) {
valueTemp = this.valueOne;
valueOne = Math.cos(valueTemp);
}
else if(ADVANCE_ACTION == TAN) {
valueTemp = this.valueOne;
valueOne = Math.tan(valueTemp);
}
else if(ADVANCE_ACTION == LOG) {
valueTemp = this.valueOne;
valueOne = Math.log(valueTemp);
}
else if(ADVANCE_ACTION == PIE) {
valueTemp = this.valueOne;
valueTemp = Math.PI;
valueOne = valueTemp;
}
else if(ADVANCE_ACTION == EXP) {
valueTemp = this.valueOne;
valueTemp = Math.E;
valueOne = valueTemp;
}
}
else {
try {
valueOne = Double.parseDouble(binding.editText.getText().toString());
}
catch (Exception e){}
}
}
}
Can anyone tell me why my app keeps on crashing?
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<layout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.anant.scientificcalculator.MainActivity">
<TextView
android:id="#+id/infoTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="30dp"
android:textSize="30sp" />
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/infoTextView"
android:enabled="false"
android:gravity="bottom"
android:hint="0"
android:inputType="numberDecimal"
android:lines="2"
android:maxLines="2"
android:textAlignment="textEnd"
android:textColor="#android:color/black"
android:textSize="40sp" />
<Button
android:id="#+id/buttonFact"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:text="#string/buttonFact"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonFact"
android:text="#string/buttonPow"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSqrt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/editText"
android:layout_toRightOf="#id/buttonPow"
android:text="#string/buttonSqrt"
android:textSize="20sp" />
<Button
android:id="#+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/buttonSqrt"
android:layout_below="#id/editText"
android:text="#string/buttonClear"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFact"
android:text="#string/buttonSine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonCosine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonPow"
android:layout_toRightOf="#id/buttonSine"
android:text="#string/buttonCosine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTangent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSqrt"
android:layout_toRightOf="#id/buttonCosine"
android:text="#string/buttonTangent"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonClear"
android:layout_toRightOf="#id/buttonTangent"
android:text="#string/buttonLog"
android:textSize="20sp" />
<Button
android:id="#+id/buttonLeftC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSine"
android:text="#string/buttonLeftC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonRightC"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonCosine"
android:layout_toRightOf="#id/buttonLeftC"
android:text="#string/buttonRightC"
android:textSize="20sp" />
<Button
android:id="#+id/buttonExp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTangent"
android:layout_toRightOf="#id/buttonRightC"
android:text="#string/buttonExp"
android:textSize="20sp" />
<Button
android:id="#+id/buttonPie"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLog"
android:layout_toRightOf="#id/buttonExp"
android:text="#string/buttonPie"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSeven"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonLeftC"
android:text="#string/buttonSeven"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEight"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonRightC"
android:layout_toRightOf="#id/buttonSeven"
android:text="#string/buttonEight"
android:textSize="20sp" />
<Button
android:id="#+id/buttonNine"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonExp"
android:layout_toRightOf="#id/buttonEight"
android:text="#string/buttonNine"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFour"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSeven"
android:text="#string/buttonFour"
android:textSize="20sp" />
<Button
android:id="#+id/buttonFive"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonEight"
android:layout_toRightOf="#id/buttonFour"
android:text="#string/buttonFive"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSix"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonNine"
android:layout_toRightOf="#id/buttonFive"
android:text="#string/buttonSix"
android:textSize="20sp" />
<Button
android:id="#+id/buttonOne"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFour"
android:text="#string/buttonOne"
android:textSize="20sp" />
<Button
android:id="#+id/buttonTwo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonFive"
android:layout_toRightOf="#id/buttonOne"
android:text="#string/buttonTwo"
android:textSize="20sp" />
<Button
android:id="#+id/buttonThree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonSix"
android:layout_toRightOf="#id/buttonTwo"
android:text="#string/buttonThree"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDot"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonOne"
android:text="#string/buttonDot"
android:textSize="20sp" />
<Button
android:id="#+id/buttonZero"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/buttonTwo"
android:layout_toRightOf="#id/buttonDot"
android:text="#string/buttonZero"
android:textSize="20sp" />
<Button
android:id="#+id/buttonEqual"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="#id/buttonNine"
android:layout_below="#id/buttonThree"
android:text="#string/buttonEqual"
android:textSize="20sp" />
<Button
android:id="#+id/buttonDivide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonNine"
android:layout_toRightOf="#id/buttonNine"
android:text="#string/buttonDIvide"
android:textSize="20sp" />
<Button
android:id="#+id/buttonMultiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonSix"
android:layout_toRightOf="#id/buttonSix"
android:text="#string/buttonMultiply"
android:textSize="20sp" />
<Button
android:id="#+id/buttonSubtract"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonThree"
android:layout_toRightOf="#id/buttonThree"
android:text="#string/buttonSubtract"
android:textSize="20sp" />
<Button
android:id="#+id/buttonAdd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/buttonEqual"
android:layout_toRightOf="#id/buttonEqual"
android:text="#string/buttonAdd"
android:textSize="20sp" />
</RelativeLayout>
</layout>

I managed to run your code with minor changes.
The problem seems to be here:
private void computeCalculation() {
if(!Double.isNaN(valueOne)) {
valueTwo = Double.parseDouble(binding.editText.getText().toString());
binding.editText.setText(null);
If you check down below the Android Monitor after the crash you will see something like this:
04-10 13:01:01.531 20742-20742/com.johnurrutia.so_43315233 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.johnurrutia.so_43315233, PID: 20742
java.lang.NumberFormatException: Invalid double: ""
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.parseDouble(StringToReal.java:267)
at java.lang.Double.parseDouble(Double.java:301)
at com.johnurrutia.so_43315233.MainActivity.computeCalculation(MainActivity.java:303)
at com.johnurrutia.so_43315233.MainActivity.access$100(MainActivity.java:11)
...
It tells you have a FATAL EXCEPTION because of an ivalid double. Which you can track to MainActivity.java in line 303 (you will have a different line most likely).
With the debugger on that line you can check and see what is happening.
I think you are trying to convert an empty String to a Double.
The changes I did to run you code are the following.
1) In the layout file:
a) Changed the layout tag with the android name space.
b) Added an empty placeholder (not sure if its necessary or not)
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
</data>
<RelativeLayout
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.johnurrutia.so_43315233.MainActivity">
...
</layout>
c) In the EditText there is an alignment to "endText" that seems to be incompatible with the selected gravity so I just erased it.
d) As you haven't posted it, just make sure you have all your #string/stringname set in your res/values/string.xml file.
2) As you are working with Data Binding, check your Gradle App Module file. You have to have:
android {
...
dataBinding {
enabled = true
}
}
3) After that look at your files and check you see nothing in red.
4) Hit Build->Clean Project. And then Run.

you need something like this to solve your issue..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
}

Related

I am unable to evaluate string using eval()

I am trying to make a calculator application.I want to evaluate the contents of a TextView and display it as a toast message. The eval() statement throws an exception for ScriptException as below.
"Unhandled exception: javax.script.ScriptException"
Even when I have imported javax.script.ScriptException. I am not getting from why it is throwing exception.
Here is my xml code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="56dp"
android:layout_alignParentEnd="true"
android:layout_alignParentTop="true"
android:layout_marginTop="95dp"
android:textAlignment="center"
android:textSize="36sp" />
<Button
android:id="#+id/n1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="18dp"
android:layout_marginTop="194dp"
android:text="1" />
<Button
android:id="#+id/n2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/n1"
android:layout_centerHorizontal="true"
android:text="2" />
<Button
android:id="#+id/n3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignTop="#+id/n1"
android:layout_marginEnd="16dp"
android:text="3" />
<Button
android:id="#+id/n4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n1"
android:layout_centerVertical="true"
android:text="4" />
<Button
android:id="#+id/n5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="5" />
<Button
android:id="#+id/n6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_centerVertical="true"
android:text="6" />
<Button
android:id="#+id/n7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignStart="#+id/n1"
android:layout_marginBottom="194dp"
android:text="7" />
<Button
android:id="#+id/n8"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/n7"
android:layout_centerHorizontal="true"
android:text="8" />
<Button
android:id="#+id/n9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/n7"
android:text="9" />
<Button
android:id="#+id/n0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="129dp"
android:text="0" />
<Button
android:id="#+id/clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/n0"
android:text="CLEAR" />
<Button
android:id="#+id/plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="73dp"
android:text="+" />
<Button
android:id="#+id/equal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignStart="#+id/n3"
android:layout_alignTop="#+id/plus"
android:text="=" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
and here is my java code:
package com.example.poopypigeon.calx;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class MainActivity extends AppCompatActivity {
Button n1;
Button n2;
Button n3;
Button n4;
Button n5;
Button n6;
Button n7;
Button n8;
Button n9;
Button n0;
Button clear;
Button plus;
Button equal;
TextView value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
value = findViewById(R.id.textView);
n1 = findViewById(R.id.n1);
n1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"1");
}
});
n2 = findViewById(R.id.n2);
n2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"2");
}
});
n3 = findViewById(R.id.n3);
n3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"3");
}
});
n4 = findViewById(R.id.n4);
n4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"4");
}
});
n5 = findViewById(R.id.n5);
n5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"5");
}
});
n6 = findViewById(R.id.n6);
n6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"6");
}
});
n7 = findViewById(R.id.n7);
n7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"7");
}
});
n8 = findViewById(R.id.n8);
n8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"8");
}
});
n9 = findViewById(R.id.n9);
n9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"9");
}
});
n0 = findViewById(R.id.n0);
n0.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val+"0");
}
});
clear = findViewById(R.id.clear);
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
value.setText("");
}
});
plus = findViewById(R.id.plus);
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
value.setText(val + "+");
}
});
equal = findViewById(R.id.equal);
equal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String val = value.getText().toString();
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
Object ans = engine.eval(val);
Toast toast = Toast.makeText(MainActivity.this,"the ans is: "+ ans,Toast.LENGTH_SHORT);
toast.show();
}
});
}
}
PS. i need a reply as soon as possible as this is for a school project
I would do it like this to further investigate:
try{
ScriptEngineManager manager = new ScriptEngineManager()
ScriptEngine engine = manager.getEngineByExtension("js");
Object ans = engine.eval(val);
Toast toast = Toast.makeText(MainActivity.this,"the ans is: "+ ans,Toast.LENGTH_SHORT);
toast.show();
catch(ScriptEngineManager e) {
// handle exception
System.err.println("Error making calculation: " + e.getMessage());
}
EDIT: Change:
String val = value.getText().toString();
value.setText(val+"1");
You have only the value in the String val - but you need the content of value textfield. In the String val there has to be something like "4+4".
You just add numbers to the textfield but no operators.
value.setText(val+"1"); -> You just add the Number 1 to the Textfield, so after clicking some Buttons you have like this in your Textfield "512312"
Copy this import statement
import javax.script.ScriptException;
Try is code:
try {
Object ans = engine.eval(val);
System.out.println("It worked!:" + ans.toString());
}
catch (ScriptException se) {
System.out.println("Problem in eval:", se.getmessage());
}
Change ScriptException with Exception
try {
ans = engine.eval(val);
} catch (Exception e) {
e.printStackTrace();
}
You are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks
To simplify the debugging here, focus on this line:
Object ans = engine.eval(val);
Print the value of val so we can see the source that is being evaluated.
Wrap that line in a try catch block and print the full stack trace so we can see the full error diagnostic.

EditText Integer_Input_Type crashes when null

To avoid unnecessary stuff, the validate function is called when the update, delete, insert button are clicked. The problem is with the EditText with inputType="number" i.e with etPrice and etSNumber.I think,there is something wrong with the validate_price() and validate_supplier_no().Please Correct Me.
public class QueryActivity extends AppCompatActivity {
private EditText etName, etPrice, etSupplier, etSNumber;
private Button insert_btn, increment, decrement, update_btn, delete_btn, call_btn;
private TextView quantity_tv;
private int quantity_value = 0;
private TextInputLayout inputLayout_name, inputLayout_price, inputLayout_supplier, inputLayout_supplier_no;
int _id, price, quantity, supplier_no = 0;
String name, supplier;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query);
increment = findViewById(R.id.increment);
decrement = findViewById(R.id.decrement);
insert_btn = findViewById(R.id.insert_btn);
update_btn = findViewById(R.id.update_product);
delete_btn = findViewById(R.id.delete_product);
call_btn = findViewById(R.id.call_btn);
etName = findViewById(R.id.et_name);
etPrice = findViewById(R.id.et_price);
quantity_tv = findViewById(R.id.quantity);
etSupplier = findViewById(R.id.et_supplier);
etSNumber = findViewById(R.id.et_sNumber);
inputLayout_name = findViewById(R.id.textInput_name);
inputLayout_price = findViewById(R.id.textInput_price);
inputLayout_supplier = findViewById(R.id.textInput_supplier);
inputLayout_supplier_no = findViewById(R.id.textInput_supplier_no);
Intent intent = getIntent();
_id = intent.getIntExtra("_id", 0);
name = intent.getStringExtra("name");
price = intent.getIntExtra("price", 0);
quantity = intent.getIntExtra("quantity", 0);
quantity_value = quantity;
supplier = intent.getStringExtra("supplier");
supplier_no = intent.getIntExtra("supplier_no", 0);
String price_str = String.valueOf(price);
if (_id != 0) {
etName.setText(name.toString());
etPrice.setText(String.valueOf(price));
quantity_tv.setText(String.valueOf(quantity).toString());
etSupplier.setText(supplier.toString());
etSNumber.setText(String.valueOf(supplier_no));
insert_btn.setVisibility(View.GONE);
} else {
update_btn.setVisibility(View.GONE);
delete_btn.setVisibility(View.GONE);
}
//OnClickListeners
insert_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
insertProduct();
}
});
update_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
updateProduct();
}
});
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
validate(v);
deleteProduct();
}
});
//add quantity btn
increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value += 1;
display(quantity_value);
}
});
//subtract quantity btn
decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
quantity_value -= 1;
if (quantity_value <= -1) {
quantity_value = 0;
}
display(quantity_value);
}
});
call_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(supplier_no==0){
Toast.makeText(getApplicationContext(),"Please Enter Supplier Number",Toast.LENGTH_SHORT).show();
}
else {
Intent intent_call = new Intent(Intent.ACTION_DIAL, Uri.fromParts("tel", String.valueOf(supplier_no), null));
startActivity(intent_call);
}
}
});
}//onCreate Ends
public void validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
}
private boolean validate_supplier_no() {
if (TextUtils.isEmpty(etSNumber.getText().toString())) {
inputLayout_supplier_no.setError("Invalid input");
return false;
} else {
inputLayout_supplier_no.setErrorEnabled(false);
return true;
}
}
private boolean validate_supplier() {
if (etSupplier.getText().toString().isEmpty()) {
inputLayout_supplier.setError("Supplier cannot be blanked");
return false;
} else {
inputLayout_supplier.setErrorEnabled(false);
return true;
}
}
private boolean validate_price() {
if (TextUtils.isEmpty(etPrice.getText().toString())) {
inputLayout_price.setError("Invalid input");
return false;
} else {
inputLayout_price.setErrorEnabled(false);
return true;
}
}
private boolean validate_name() {
if (etName.getText().toString().isEmpty()) {
inputLayout_name.setError("Name cannot be blanked");
return false;
} else {
inputLayout_name.setErrorEnabled(false);
return true;
}
}
private void deleteProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
Uri uri = ContentUris.withAppendedId(CONTENT_URI, _id);
int rowsDeleted = getContentResolver().delete(uri, selection, selectionArgs);
}
private void updateProduct() {
String selection = _ID + " = ? ";
String[] selectionArgs = {String.valueOf(_id)};
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
int rowsUpdated = getContentResolver().update(uri, values, selection, selectionArgs);
Toast.makeText(this, "Item inserted at: " + rowsUpdated, Toast.LENGTH_SHORT).show();
}
private void insertProduct() {
String et_productName = etName.getText().toString();
int et_productPrice = Integer.parseInt(etPrice.getText().toString());
int tv_productQuantity = Integer.parseInt(quantity_tv.getText().toString());
String et_productSupplier = etSupplier.getText().toString();
int et_productSNumber = Integer.parseInt(etSNumber.getText().toString());
ContentValues values = new ContentValues();
values.put(PRODUCT_NAME, et_productName);
values.put(PRICE, et_productPrice);
values.put(QUANTITY, tv_productQuantity);
values.put(SUPPLIER, et_productSupplier);
values.put(SUPPLIER_NO, et_productSNumber);
Uri uri = CONTENT_URI;
Uri uriRowsInserted = getContentResolver().insert(uri, values);
Toast.makeText(this, "Item inserted at: " + uriRowsInserted, Toast.LENGTH_SHORT).show();
}
//for updating the quantity_tv
public void display(int number) {
quantity_tv.setText(String.valueOf(number));
}
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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="#e0e0e0"
android:orientation="vertical"
tools:context=".QueryActivity"
>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_name"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_price"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_price"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Product Price..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button
android:id="#+id/increment"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="+" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="0"
android:textSize="24sp" />
<Button
android:id="#+id/decrement"
android:layout_width="55dp"
android:layout_height="wrap_content"
android:text="-" />
</LinearLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_supplier"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Supplier Name..."
android:inputType="text" />
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:id="#+id/textInput_supplier_no"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/et_sNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter SupplierNumber..."
android:inputType="number" />
</android.support.design.widget.TextInputLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<Button
android:id="#+id/insert_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="ADD IT" />
<Button
android:id="#+id/delete_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="DELETE IT" />
<Button
android:id="#+id/update_product"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:background="#drawable/button_layout"
android:text="Save Changes" />
<Button
android:id="#+id/call_btn"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:background="#drawable/button_layout"
android:drawableLeft="#drawable/call"
android:drawablePadding="-40dp"
android:text="CALL" />
</LinearLayout>
</LinearLayout>
Note: With Empty etPrice or etSNumber,this code throws java.lang.NumberFormatException: Invalid int: ""
You should call insertProduct, deleteProduct and updateProduct only if inputs are valid. Change your method validate like below
public boolean validate(View view) {
try {
if (validate_name() && validate_price() && validate_supplier() && validate_supplier_no()) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
return true;
}
}
catch (NumberFormatException e){
Toast.makeText(getApplicationContext(), "Not Success!", Toast.LENGTH_SHORT).show();
}
return false;
}
and start using as
delete_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(validate(v)) {
deleteProduct();
}
}
});
you can Set Error for your EditText not for your Layout.So you car rewrite your code by this way:
etPrice.setError ("Price cannot be blanked");
return false;
} else {
etPrice.setErrorEnabled(false);
return true;

Calculator code(enter new number and clear Button)in android

I'm new to Android programming(Android Studio).I'm trying to write a calculator code but I run into sum problems
for example I enter 3 at first then clicks + and then number 5.After clicking on any operator result will appear but when I want to enter a new number for calculation the result will not remove and new number sticks to that.(for example result is 8 and new number is 4;after entering 4 it will be 8.04 in text view instead of 4!)
when I click clear button and want to do a new calculation the calculator doesn't work currectly
here is my present code.Any one can help me?Thanks a lot :)
public class MainActivity extends AppCompatActivity {
float firstNumber,secondNumber,result;
TextView display;
Button one,two,three,four,five,six,seven,eight,nine,zero,exe,clear,multiply,divide,sum,minus;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView) findViewById(R.id.khali);
one = (Button) findViewById(R.id.adade1);
two = (Button) findViewById(R.id.adade2);
three = (Button) findViewById(R.id.adade3);
four = (Button) findViewById(R.id.adade4);
five = (Button) findViewById(R.id.adade5);
six = (Button) findViewById(R.id.adade6);
seven = (Button) findViewById(R.id.adade7);
eight = (Button) findViewById(R.id.adade8);
nine = (Button) findViewById(R.id.adade9);
zero = (Button) findViewById(R.id.adade0);
multiply = (Button) findViewById(R.id.zarb);
divide = (Button) findViewById(R.id.taghsim);
sum = (Button) findViewById(R.id.jam);
minus = (Button) findViewById(R.id.menha);
exe = (Button) findViewById(R.id.mosavi);
clear = (Button) findViewById(R.id.pak);
final Button[] operators = new Button[5];
operators[0] = multiply;
operators[1] = divide;
operators[2] = sum;
operators[3] = minus;
operators[4] = exe;
final Button[] numbers = new Button[10];
numbers[0] = zero;
numbers[1] = one;
numbers[2] = two;
numbers[3] = three;
numbers[4] = four;
numbers[5] = five;
numbers[6] = six;
numbers[7] = seven;
numbers[8] = eight;
numbers[9] = nine;
for (int a = 0; a < 10; a++) {
final int finalA = a;
numbers[a].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText(display.getText() + String.valueOf(finalA));
if (isResult(display)==false) {
display.setText("");
display.setText(display.getText() + String.valueOf(finalA));
}
}
});
}
clear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
display.setText("");
}
});
sum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (display.getText() == null) {
display.setText("");
} else {
firstNumber = parseFloat(display.getText().toString());
display.setText("");
for (int i=0;i<5;i++){
operators[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondNumber=parseFloat(display.getText().toString());
result=firstNumber+secondNumber;
display.setText(String.valueOf(result));
}
});
}
}
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstNumber = parseFloat(display.getText().toString());
display.setText("");
for (int i=0;i<5;i++){
operators[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondNumber=parseFloat(display.getText().toString());
result=firstNumber-secondNumber;
display.setText(String.valueOf(result));
}
});
}
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstNumber = parseFloat(display.getText().toString());
display.setText("");
for (int i=0;i<5;i++){
operators[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondNumber=parseFloat(display.getText().toString());
result=firstNumber*secondNumber;
display.setText(String.valueOf(result));
}
});
}
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firstNumber=parseFloat(display.getText().toString());
display.setText("");
for (int i=0;i<5;i++){
operators[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
secondNumber=parseFloat(display.getText().toString());
result=firstNumber/secondNumber;
display.setText(String.valueOf(result));
}
});
}
}
});
}
private boolean isResult(TextView abc){
while (abc.getText()==String.valueOf(result)){
return false;
}
return true;
}
}
If you are new to android i suggest using a simpler method so that you can understand how the code works, Here is a simple calculator code that will make more sense:
firstNumEditText = (EditText) findViewById(R.id.firstNumeditText);
secondNumEditText = (EditText) findViewById(R.id.secondNumeditText);
resultTextView = (TextView) findViewById(R.id.resultTextView);
addBtn = (Button) findViewById(R.id.addBtn);
subtractBtn = (Button) findViewById(R.id.subtractBtn);
multiplyBtn = (Button) findViewById(R.id.multiplyBtn);
divideBtn = (Button) findViewById(R.id.divideBtn);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 + num2;
resultTextView.setText(result + "");
}
});
subtractBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 - num2;
resultTextView.setText(result + "");
}
});
multiplyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 * num2;
resultTextView.setText(result + "");
}
});
divideBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int num1 = Integer.parseInt(firstNumEditText.getText().toString());
int num2 = Integer.parseInt(secondNumEditText.getText().toString());
int result = num1 / num2;
resultTextView.setText(result + "");
}
});
}
and here is the XML:
<EditText
android:id="#+id/firstNumeditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Enter 1st number"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="#+id/secondNumeditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:ems="10"
android:hint="Enter 2nd number"
android:inputType="number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/firstNumeditText" />
<Button
android:id="#+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Add"
app:layout_constraintBottom_toTopOf="#+id/resultTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.275"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondNumeditText" />
<TextView
android:id="#+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Result"
android:textSize="30sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondNumeditText"
app:layout_constraintVertical_bias="0.742" />
<Button
android:id="#+id/subtractBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="subtract"
app:layout_constraintBottom_toTopOf="#+id/resultTextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.721"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/secondNumeditText" />
<Button
android:id="#+id/multiplyBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="28dp"
android:text="multiply"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.277"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addBtn" />
<Button
android:id="#+id/divideBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="28dp"
android:text="divide"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.728"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/subtractBtn" />

Application can't run properly while using spinner in Android

application terminated when using the Button in Layout
I have used spinner widget for my application & switch statements...
this is my mainactivity.java file
package com.example.edward.converter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import static java.lang.System.exit;
public class MainActivity extends AppCompatActivity {
private Button btn;
private TextView txt;
private EditText etxt;
private Spinner spn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
txt = (TextView) findViewById(R.id.textView);
etxt = (EditText) findViewById(R.id.editText);
spn = (Spinner) findViewById(R.id.spinner);
spn.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 2.54;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " cm" ));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 1 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.393701;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Inch"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 2 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.0254;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Metre"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 3 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 39.9701;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + "Inch"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 4 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 0.01;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " Metre"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
case 5 :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double result = 0.0;
double multiplier = 100;
if(etxt.getText().toString().equals("")){
txt.setText(R.string.error);
txt.setTextColor(Color.RED);
}else {
double valueMetre = Double.parseDouble(etxt.getText().toString());
result = valueMetre*multiplier;
txt.setText(String.format("%.2f",result + " cm"));
txt.setVisibility(v.VISIBLE);
txt.setTextColor(Color.WHITE);
}
}
});
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
exit(0);
}
});
}
}
& this is activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
android:background="#drawable/blue"
tools:context="com.example.edward.converter.MainActivity">
<Spinner
android:id="#+id/spinner"
android:layout_width="205dp"
android:layout_height="46dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:entries="#array/convert"
android:gravity="center"
android:longClickable="false"
android:spinnerMode="dialog"
app:layout_constraintBottom_toTopOf="#+id/editText"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<ImageView
android:id="#+id/imageView"
android:layout_width="72dp"
android:layout_height="71dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:contentDescription="#string/todo"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/converter" />
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="38dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="96dp"
android:background="#drawable/circular"
android:ems="10"
android:gravity="center"
android:hint="#string/enter_value"
android:inputType="textPersonName|number"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.503"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/imageView" />
<Button
android:id="#+id/button"
android:layout_width="112dp"
android:layout_height="39dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:background="#drawable/circular"
android:longClickable="true"
android:text="#string/convert"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText"
app:layout_constraintVertical_bias="0.189" />
<TextView
android:id="#+id/textView"
android:layout_width="398dp"
android:layout_height="45dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:gravity="center"
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button" />
</android.support.constraint.ConstraintLayout>
This is what i have used in strings.xml
<resources>
<string name="app_name">Converter</string>
<string name="enter_value">Enter Value</string>
<string name="todo">TODO</string>
<string name="convert">Convert</string>
<string name="error">Please Enter A Valid Number</string>
<string-array name="convert">
<item>Inch-cm</item>
<item>cm-Inch</item>
<item>Inch-Metre</item>
<item>Metre-Inch</item>
<item>cm-Metre</item>
<item>Metre-cm</item>
</string-array>
</resources
layout:
Please Help in understanding this spinner concept & this error...

Android App crashed and showing a white blank Screen

Note: Sorry if my problem may be really easy to fix, I'm a total beginner in this, I literally started learning this just 2 days ago.
So anyway, I'm making this basic calculator app for androids. I built the .apk and sent it to my phone but it just shows a blank white screen and then it crashes. Here's the xml code and the java code:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:background="#drawable/numbs" >
<TextView
android:id="#+id/title"
android:text="Calculator"
android:textColor="#E11608"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="35sp"
android:layout_gravity="top|center"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#000000"
/>
<EditText
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:inputType="number"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:layout_gravity="center"
android:layout_marginBottom="80dp"
android:hint="Type in your next value"
/>
<EditText
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:inputType="number"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:ems="10"
android:layout_gravity="center"
android:layout_marginBottom="148dp"
android:hint="Type in your first value"
/>
<Button
android:id="#+id/add"
android:text="+"
android:layout_gravity="center|left"
android:onClick="onClick"
/>
<Button
android:id="#+id/minus"
android:text="-"
android:layout_gravity="center"
android:layout_marginRight="40dp"
android:onClick="onClick"
/>
<Button
android:id="#+id/divide"
android:text="÷"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:onClick="onClick"
/>
<Button
android:id="#+id/multiply"
android:text="×"
android:layout_gravity="center|right"
android:onClick="onClick"
/>
<TextView
android:id="#+id/answer"
android:text="Your answer should display here"
android:textColor="#E11608"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10sp"
android:layout_gravity="bottom|center"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="40dp"
android:background="#FFFFFF"
/>
</FrameLayout>
Java code:
package com.Drift.app;
import android.app.*;
import android.os.*;
import java.io.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;
public class MainActivity extends Activity
{
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
work();
}
public void work()
{
//create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id. title);
final TextView answer = (TextView) findViewById(R.id. answer);
final EditText value1 = (EditText) findViewById(R.id. value1);
final EditText value2 = (EditText) findViewById(R.id. value2);
val1 = Integer.parseInt(value1.getText().toString());
final Integer val1 = new Integer(value1.getText().toString());
val2 = Integer.parseInt(value2.getText().toString());
final Integer val2 = new Integer(value2.getText().toString());
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
Sorry for not commenting much. Can someone please tell me what I did wrong or maybe propose a better code. P.s sorry again if nearly everything here is wrong but like I said, I'm a total beginner. Thanks.
Okay, thanks for the answers this is is what I ended up with
package com.Drift.app;
import android.app.*;
import android.os.*;
import java.io.*;
import android.widget.*;
import android.view.View.*;
import android.view.*;
public class MainActivity extends Activity
{
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
work();
}
public void work()
{
//create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id. title);
final TextView answer = (TextView) findViewById(R.id. answer);
final EditText value1 = (EditText) findViewById(R.id. value1);
final EditText value2 = (EditText) findViewById(R.id. value2);
if(value1.getText()!=null)
{val1 = Integer.parseInt(value1.getText().toString());}
if(value2.getText()!=null)
{val2 = Integer.parseInt(value2.getText().toString());}
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
But it's still giving me a blank white page, I'm using gradle by the way
Here's the Android manifest file
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.Drift.app" >
<application
android:allowBackup="true"
android:icon="#drawable/calc"
android:label="#string/app_name"
android:theme="#android:style/Theme.Holo.Light" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
java.lang.RuntimeException: Binary XML file line #51: You must supply a layout_width attribute.
All views must have android:layout_width and android:layout_height defined. At least your Buttons don't have either.
Try to check EditText value before use it :
if(value1.getText().toString().trim().length()>0){
val1 = Integer.parseInt(value1.getText().toString());
}
if(value2.getText().toString().trim().length()>0){
val2 = Integer.parseInt(value2.getText().toString());
}
It is a probably a problem with a parsing. You are getting value from empty editText. You should not do that in on create method. You should check if value2 and value1 are null before using it.
if(value2.getText()!=null){val2 = Integer.parseInt(value2.getText().toString());}
here is the full working code. i have executed this and its working fine.
ur activity
public class MainAvtivity extends Activity {
int val1;
int val2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seekbar);
work();
}
public void work() {
// create parameter for add button
Button add = (Button) findViewById(R.id.add);
Button multiply = (Button) findViewById(R.id.multiply);
Button minus = (Button) findViewById(R.id.minus);
Button divide = (Button) findViewById(R.id.divide);
TextView title = (TextView) findViewById(R.id.title);
final TextView answer = (TextView) findViewById(R.id.answer);
final EditText value1 = (EditText) findViewById(R.id.value1);
final EditText value2 = (EditText) findViewById(R.id.value2);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 + val2));
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 * val2));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 - val2));
}
});
divide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (!"".equals(value1.getText().toString())) {
val1 = Integer.parseInt(value1.getText().toString());
}
if (!"".equals(value2.getText().toString())) {
val2 = Integer.parseInt(value2.getText().toString());
}
answer.setText(String.valueOf(val1 / val2));
}
});
}
}
and u have not specified height and weight in xml.
try this xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/numbs"
android:gravity="center" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_gravity="top|center"
android:background="#000000"
android:text="Calculator"
android:textColor="#E11608"
android:textSize="35sp" />
<EditText
android:id="#+id/value1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="80dp"
android:background="#FFFFFF"
android:ems="10"
android:hint="Type in your next value"
android:inputType="number" />
<EditText
android:id="#+id/value2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_gravity="center"
android:layout_marginBottom="148dp"
android:background="#FFFFFF"
android:ems="10"
android:hint="Type in your first value"
android:inputType="number" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|left"
android:onClick="onClick"
android:text="+" />
<Button
android:id="#+id/minus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="40dp"
android:onClick="onClick"
android:text="-" />
<Button
android:id="#+id/divide"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="40dp"
android:onClick="onClick"
android:text="÷" />
<Button
android:id="#+id/multiply"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|right"
android:onClick="onClick"
android:text="×" />
<TextView
android:id="#+id/answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_gravity="bottom|center"
android:layout_marginBottom="40dp"
android:background="#FFFFFF"
android:text="Your answer should display here"
android:textColor="#E11608"
android:textSize="10sp" />
</FrameLayout>

Categories

Resources