How to make the "Split it!" button work in my app? - android

This is one of my first app projects and I am pretty excited! I cannot make the "split" button work (it has to divide the total by the number of people set in "people"). The first percentage buttons work fine, but not the last "split it!".
I am learning a lot and I love it!
xml.file
<?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:id="#+id/activiy_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:paddingBottom="16dp"
tools:context="com.example.dell.calculator.MainActivity"
android:weightSum="1">
<EditText
android:id="#+id/subtotal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Subtotal"
android:inputType="number|numberDecimal" />
<EditText
android:id="#+id/itbms"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="ITBMS"
android:inputType="number|numberDecimal" />
<Button
android:id="#+id/diez"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="10%" />
<Button
android:id="#+id/quince"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="15%" />
<Button
android:id="#+id/veinte"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="20%" />
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.18"
android:text="TOTAL"
android:textSize="25dp"
android:inputType="numberDecimal"/>
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Number of People"
android:layout_weight="0.09" />
<EditText
android:id="#+id/people"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:textSize="25dp"
android:inputType="number" />
<Button
android:id="#+id/split"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Split It!" />
<EditText
android:id="#+id/finalresult"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.55"
android:ems="10"
android:hint="EACH"
android:inputType="numberDecimal" />
</LinearLayout>
Mainactivity.java
package com.example.dell.calculator;
import android.icu.text.NumberFormat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Locale;
import static com.example.dell.calculator.R.id.add;
public class MainActivity extends AppCompatActivity {
TextView result, finalresult;
EditText subtotal, itbms, people;
Button diez, quince, veinte, split;
float result_num, result_num2;
int num1, num2, num3, num4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
finalresult = (TextView) findViewById(R.id.finalresult);
itbms = (EditText) findViewById(R.id.itbms);
subtotal = (EditText) findViewById(R.id.subtotal);
diez = (Button) findViewById(R.id.diez);
quince = (Button) findViewById(R.id.quince);
veinte = (Button) findViewById(R.id.veinte);
diez.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1 = Integer.parseInt(subtotal.getText().toString());
num2 = Integer.parseInt(itbms.getText().toString());
result_num = (float) ((num1 + num2) * 1.10);
result.setText(String.valueOf(result_num));
}
});
quince.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1 = Integer.parseInt(subtotal.getText().toString());
num2 = Integer.parseInt(itbms.getText().toString());
result_num = (float) ((num1 + num2) * 1.15);
result.setText(String.valueOf(result_num));
}
});
veinte.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1 = Integer.parseInt(subtotal.getText().toString());
num2 = Integer.parseInt(itbms.getText().toString());
result_num = (float) ((num1 + num2) * 1.20);
result.setText(String.valueOf(result_num));
}
});
split.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num4 = (int) result_num;
num3 = Integer.parseInt(people.getText().toString());
result_num2 = (float) num4 / num3;
finalresult.setText(String.valueOf(result_num2));
}
});
}
}

This is totally normal, for beginners.I would recommend you to Declare and initialize View Objects(Button,TextView..etc)
simultaneously.
Button split = (Button) findViewById(R.id.split);

You forgot to obtain the button view reference:
Change this:
diez = (Button) findViewById(R.id.diez);
quince = (Button) findViewById(R.id.quince);
veinte = (Button) findViewById(R.id.veinte);
for this:
diez = (Button) findViewById(R.id.diez);
quince = (Button) findViewById(R.id.quince);
veinte = (Button) findViewById(R.id.veinte);
split = (Button) findViewById(R.id.split);
This kind of errors can be detected by reading the app log. I am sure that a NullPointerException ocurrs caused by the invokation of split.setOnClickListener (split was null).

Related

I just created a simple calculator app but when I input a decimal number the application crashes

Here is my code for the add function.
public void add(View v)
{
EditText e1=(EditText)findViewById(R.id.et1);
EditText e2=(EditText)findViewById(R.id.et2);
TextView tv=(TextView)findViewById(R.id.tv);
long num1,num2,result;
num1=Long.parseLong(e1.getText().toString());
num2=Long.parseLong(e2.getText().toString());
result=num1+num2;
tv.setText(Long.toString(result));
}
Try the following:
Calculator.class:------------------
public class Calculator extends AppCompatActivity {
private EditText edt1;
private EditText edt2;
private TextView tv_res;
private Button b_cal;
Float num1,num2,result;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
edt1 = (EditText) findViewById(R.id.edt1);
edt2 = (EditText) findViewById(R.id.edt2);
tv_res = (TextView) findViewById(R.id.tv_res);
b_cal = (Button) findViewById(R.id.b_cal);
b_cal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
num1 = Float.parseFloat(edt1.getText().toString());
num2 = Float.parseFloat(edt2.getText().toString());
result = num1 + num2;
tv_res.setText(String.valueOf(result));
}
});
}
}
calculator.xml:------------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter First Number"
android:id="#+id/edt1"
android:inputType="numberDecimal|numberSigned" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="16sp"
android:text="+"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter Second Number"
android:id="#+id/edt2"
android:inputType="numberDecimal|numberSigned"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:gravity="center"
android:textSize="16sp"
android:rotation="90"
android:hint="=" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:id="#+id/tv_res"
android:hint="Result" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:id="#+id/b_cal"
android:text="Calculate"/>
</LinearLayout>
Change your datatype from long to double, will fix your problem because you cannot parse a floating point value to a long.

how to make number picker work in fragment with on clicklistener

I have a tab layout, number picker in the fragment doesn't seem to be working, the values remain 0 always.
Basically I am making random number app.
there are three number pickers in my fragment, one gives minimum number, one gives maximum number and one gives quantity of random numbers.
after setting these values in number picker user hits a button to get random numbers.
for me button is not doing anything when the values are set.
Please suggest me how to do this.
My fragment activity
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.NumberPicker;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
public class TabFragment2 extends Fragment {
//declare Spinner object
Spinner generatorType;
Button getRandomNumberBtn;
int minimumNumber;
int maximumNumber;
int quantity1;
TextView randNumbText;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab_fragment_2, container, false);
getRandomNumberBtn = (Button) view.findViewById(R.id.get_number);
NumberPicker miniText;
final TextView minimumTextView = (TextView) view.findViewById(R.id.textView3);
miniText = (NumberPicker) view.findViewById(R.id.start_number);
miniText.setMinValue(0);
miniText.setMaxValue(10000);
miniText.setWrapSelectorWheel(true);
miniText.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal1, int newVal1) {
//Display the newly selected number from picker
minimumTextView.setText("Min: " + newVal1);
}
});
minimumNumber = miniText.getValue();
NumberPicker maxiText;
final TextView maximumTextView = (TextView) view.findViewById(R.id.textView2);
maxiText = (NumberPicker) view.findViewById(R.id.end_number);
maxiText.setMinValue(0);
maxiText.setMaxValue(10000);
maxiText.setWrapSelectorWheel(true);
maxiText.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal2, int newVal2) {
//Display the newly selected number from picker
maximumTextView.setText("Max: " + newVal2);
}
});
maximumNumber = maxiText.getValue();
NumberPicker quantity;
final TextView quantityTextView = (TextView) view.findViewById(R.id.quantity_text);
quantity = (NumberPicker) view.findViewById(R.id.quantity_picker);
quantity.setMinValue(0);
quantity.setMaxValue(100);
quantity.setWrapSelectorWheel(true);
quantity.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal3, int newVal3) {
//Display the newly selected number from picker
quantityTextView.setText("Quantity: " + newVal3);
}
});
quantity1 = quantity.getValue();
randNumbText = (TextView) view.findViewById(R.id.random_number_display);
getRandomNumberBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int b = maximumNumber + 1;
int a = minimumNumber;
int c = quantity1;
String multipleRandoms = "";
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list1 = new ArrayList<Integer>();
for (int i = a; i < b; i++) {
list.add(new Integer(i));
}
int k = list.size();
Collections.shuffle(list);
if (k>c) {
for (int i = 1; i <= c; i++) {
list1.add(new Integer(list.get(i)));
multipleRandoms = list1.toString();
}
}else if (k==c) {
multipleRandoms = list.toString();
} else {
Toast toast = Toast.makeText(getActivity(),"Quantity can not be greater than numbers in range", Toast.LENGTH_LONG);
toast.show();
}
randNumbText.setText(multipleRandoms);
}
});
return view;
}
My fragment layout
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/tab_fragment_2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="com.example.tabstrial2.TabFragment2">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="#dimen/activity_vertical_margin">
<LinearLayout
android:id="#+id/linear_layout1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/generator_type_spinner"
android:orientation="horizontal">
<LinearLayout
android:id="#+id/linear_layout2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Min" />
<NumberPicker
android:id="#+id/start_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
<LinearLayout
android:layout_width="2px"
android:layout_height="match_parent"
android:background="#android:color/black">
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/quantity_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Quantity" />
<NumberPicker
android:id="#+id/quantity_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
<LinearLayout
android:layout_width="2px"
android:layout_height="match_parent"
android:background="#android:color/black">
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10px"
android:text="Max" />
<NumberPicker
android:id="#+id/end_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView2"
android:layout_gravity="center_horizontal"
android:layout_marginBottom="20px"
android:layout_marginTop="20px" />
</LinearLayout>
</LinearLayout>
<TextView
android:id="#+id/random_number_display"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linear_layout1"
android:layout_centerHorizontal="true"
android:layout_margin="10px"
android:textColor="#android:color/black"
android:textSize="40dp" />
<Button
android:id="#+id/get_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/random_number_display"
android:layout_centerHorizontal="true"
android:background="#android:color/holo_orange_light"
android:focusable="true"
android:focusableInTouchMode="true"
android:onClick="getRandomNumber"
android:paddingLeft="20px"
android:paddingRight="20px"
android:text="Get Random Number" />
</RelativeLayout>
</ScrollView>

Getting value from dynamically created textview in android

MainActivity's code
How can I get values from the text boxes and the qty box in that user will input the value. price will come from server and than i want to calculate the bill and show it in next layout. plz give me some easy explanation as i am not expert in it. thanks in advance.
MainActivity .java
package com.example.myone;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
EditText textIn;
Button buttonAdd;
LinearLayout container;
private Button done;
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textIn = (EditText)findViewById(R.id.textin);
buttonAdd = (Button)findViewById(R.id.add);
container = (LinearLayout)findViewById(R.id.container);
done = (Button) findViewById(R.id.cal);
tv= (TextView) findViewById(R.id.tv);
buttonAdd.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView textOut = (TextView)addView.findViewById(R.id.textout);
textOut.setText(textIn.getText().toString());
//(int1);
Button buttonRemove = (Button)addView.findViewById(R.id.remove);
buttonRemove.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
((LinearLayout)addView.getParent()).removeView(addView);
}});
container.addView(addView);
}});
}
}
MainActivity.xml
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:orientation="vertical"
android:background="#drawable/mainbg"
tools:context=".MainActivity" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="#+id/textin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Enter your item here"
/>
<Button
android:id="#+id/cal"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="#+id/textin"
android:text="Done!"
android:layout_alignParentLeft="true"
/>
<Button
android:id="#+id/add"
android:text="Add"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignBaseline="#+id/cal"
/>
</RelativeLayout>
<LinearLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Row.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:background="#drawable/borderbg"
android:orientation="horizontal"
android:id="#+id/rel"
android:layout_height="wrap_content">
<TextView
android:id="#+id/textout"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:hint="Item"
android:layout_marginTop="10dp"
android:layout_marginLeft="5dp"
/>
<EditText
android:id="#+id/qty"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_alignTop="#+id/price"
android:layout_toRightOf="#+id/price"
android:layout_marginLeft="50dp"
android:textSize="12sp"
android:hint="Qty" />
<TextView
android:id="#+id/price"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textout"
android:layout_alignBottom="#+id/textout"
android:layout_marginLeft="42dp"
android:layout_toRightOf="#+id/textout"
android:hint="Price" />
<Button
android:id="#+id/remove"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="left"
android:text="remove" />
</RelativeLayout>
Simply I want to create a basic shopping app that have 20 products. the price and product name will come from server and quantity will input by user so how do I that?
You are looking for something like this
int count = container.getChildCount();
for (int i = 0; i < count; i++) {
final View row = container.getChildAt(i);
TextView textOut = (TextView)row.findViewById(R.id.textout);
String data = textOut.getText().toString();
}
Where container is your LinearLayout in which you have added your inflated rows.
Try this:-
To take user input from text box:-
int qty = Integer.parseInt(qtyTextBox.getText().toString());
Caluculate bill:-
double bill = price*qty;
Send bill value to next activity:-
Intent in = new Intent();
in.putExtra("Bill", bill);
startActivity(in);
Get bill value in next activity:-
Intent in = getIntent();
int mBill = in.getExtra("Bill");
string bill = String.valueOf(mBill);
Now you can set the value of 'bill' to the TextView where you want to display it.

Simple calculator application in Android

When I click on the add button without entring anything on the edittext,unfortunately calculator has stopped.
package com.example.calculator;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Calci extends Activity {
TextView t1;
EditText e1,e2;
Button add,sub,mul,div;
Context c;;
String b,a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
e1=(EditText) findViewById(R.id.EditText01);
e2=(EditText) findViewById(R.id.EditText02);
add=(Button) findViewById(R.id.add);
sub=(Button) findViewById(R.id.sub);
mul=(Button) findViewById(R.id.mul);
div=(Button) findViewById(R.id.div);
t1=(TextView) findViewById(R.id.textView1);
a=e1.getText().toString();
b=e2.getText().toString();
}
public void doSomething(View v){
if(v.getId()==R.id.add){
if (a==null & b==null){
Toast.makeText(c,"PLEASE ENTER SOMETHING", Toast.LENGTH_LONG).show();
}
else{
int result=Integer.parseInt(a) + Integer.parseInt(b);
t1.setText(Integer.toString(result));
}
}
}
}
When I click on the add button,unfortunately calculator has stopped.
XML FILE
<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"
tools:context=".Calci" >
<EditText
android:id="#+id/EditText01"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10"
android:inputType="number" />
<EditText
android:id="#+id/EditText02"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/EditText01"
android:ems="10"
android:inputType="number" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/EditText01"
android:layout_marginTop="20dp"
android:text="ADD"
android:onClick="doSomething"/>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button4"
android:layout_marginTop="44dp"
android:gravity="center"
android:textAppearance="?android:attr/textAppearanceLarge" />
<Button
android:id="#+id/sub"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/add"
android:onClick="doSomething"
android:text="SUBTRACT" />
<Button
android:id="#+id/mul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/sub"
android:onClick="doSomething"
android:text="MULTIPLY" />
<Button
android:id="#+id/div"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/mul"
android:onClick="doSomething"
android:text="DIVIDE" />
</RelativeLayout>
When I click on the add button,unfortunately calculator has stopped.\
what shuold i do now
First of all initialize
t1=(TextView) findViewById(R.id.textView1);
And you can put validation for empty check on button click listener before furthe process like
if(!(t1.getText.toString().equals(""))) to show alerts
I think problem is that you have not declared your text-view, try to declare it like below and then try.
t1=(TextView) findViewById(R.id.textView1);
Edit
if (e1.getText.toString().trim() == "" && e2.getText.toString().trim() == "")
{
// alert
}
else
{
// do your code
}
So your final code would be
public void doSomething(View v){
if(v.getId()==R.id.add){
a=e1.getText().toString();
b=e2.getText().toString();
if (a == "" && b == "")
{
// alert
}
else
{
int result=Integer.parseInt(a) + Integer.parseInt(b);
t1.setText(Integer.toString(result));
}
}
}
At first you have mistake in your function - you should call e1.setText(), not t1, t1 undeclared and not initialized. And next you should use OnClickListener like this:
public class Calci extends Activity {
TextView t1;
EditText e1,e2;
Button add,sub,mul,div;
String b,a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calci);
e1=(EditText) findViewById(R.id.EditText01);
e2=(EditText) findViewById(R.id.EditText02);
add=(Button) findViewById(R.id.add);
sub=(Button) findViewById(R.id.sub);
mul=(Button) findViewById(R.id.mul);
div=(Button) findViewById(R.id.div);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
a=e1.getText().toString();
b=e2.getText().toString();
int result=Integer.parseInt(a) + Integer.parseInt(b);
e1.setText(Integer.toString(result));
}
});
}
}
And yes, check the textfield for not empty String.
if((!a.isEmpty())&(!b.isEmpty())) { your code }
And the best way - use try-catch for catching FormatNumberException
try {
int result=Integer.parseInt(a) + Integer.parseInt(b);
e1.setText(Integer.toString(result));
}
catch (FormatNumberException e) {
Log.d("Exception", e.getMessage());
}
So you can prevent all crashes.

multiply with zero, double no number

I am trying to build a calculator for android, i am trying to multiply two numbers.
If i give number 1 and leave number 2 open, i want to get zero as an answer.
I first thought it could be the problem of not having a value for the double.
So i tried: if (Double.isNaN(number1)) { number1=0; }
But it did not work.
How do i make this happen?
R.layout.main:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- 1 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- 2 -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="number:" />
<EditText
android:id="#+id/number2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="0"
android:inputType="number"
android:layout_marginLeft="20dp" />
</LinearLayout>
<!-- multiply -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="multiply:" />
<TextView
android:id="#+id/multiplydisplay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="20dp" />
</LinearLayout>
<Button
android:id="#+id/btncalculate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"/>
<Button
android:id="#+id/btnreset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Reset" />
</LinearLayout>
TipcalcActivity.java
package com.tip.calc;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Button;
import android.view.View;
public class TipcalcActivity extends Activity {
private EditText number1;
private EditText number2;
private TextView multiplydisplay;
private Button btncalculate;
private Button btnreset;
private double number1calc = 0;
private double number2calc = 0;
private double multiply = 0;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initControls();
}
private void initControls() {
number1 = (EditText)findViewById(R.id.number1);
number2 = (EditText)findViewById(R.id.number2);
multiplydisplay = (TextView)findViewById(R.id.multiplydisplay);
btncalculate = (Button)findViewById(R.id.btncalculate);
btnreset = (Button)findViewById(R.id.btnreset);
btncalculate.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ calculate(); }});
btnreset.setOnClickListener(new Button.OnClickListener() { public void
onClick (View v){ reset(); }});
}
private void calculate() {
number1calc=Double.parseDouble(number1.getText().toString());
number2calc=Double.parseDouble(number2.getText().toString());
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
private void reset() {
multiplydisplay.setText("");
number1.setText("");
number2.setText("");
}
}
you should just check that the content of the textfield of the value is different than "". If not, just assign the value 0.
In calculate :
private void calculate() {
number1calc=(number1.getText().toString() != "" ) ? Double.parseDouble(number1.getText().toString()) : 0;
number2calc=(number2.getText().toString() != "" ) ? Double.parseDouble(number2.getText().toString()) : 0;
multiply=(number1calc*number2calc);
multiplydisplay.setText(Double.toString(multiply));
}
if(numberOne.getText().toString().trim().length() < 1 || numberTwo.getText().toString().length() < 1){
multiplyDisplay.setText("0");
}
else{
//default handling
}
If the edittext is left blank, this is obviously not a number(NaN). Doing any operation with NaN in Java will cause the result of this operation to be NaN.

Categories

Resources