How to handle not filled EditText in Android - android

I want to code a simple calculator with 3 inputs (NUM1,NUM2,NUM3), 3 buttons(SUM,SUB,MUL) and 1 RESULT text plane. In my app if I give all inputs, the app works correctly. However if I don't give any input for 1 field, I encounter app stopped error. I want to make my app work with any number of inputs.
Here is my code.
public void onButtonClickSum(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
public void onButtonClickSub(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sub = num1 - num2 - num3;
t1.setText(Integer.toString(sub));
}
public void onButtonClickMul(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
EditText e3 = (EditText)findViewById(R.id.editText3);
TextView t1 = (TextView)findViewById(R.id.textView2);
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int mul = num1 * num2 * num3;
t1.setText(Integer.toString(mul));
}

You need to put null or empty checks before you parse the input as integers
Try making the EditText objects fields, since you are reusing them in each method
Example:
// Fields
private EditText mEditText1 = (EditText)findViewById(R.id.editText);
private EditText mEditText2 = (EditText)findViewById(R.id.editText2);
private EditText mEditText3 = (EditText)findViewById(R.id.editText3);
private TextView mTextView = (TextView)findViewById(R.id.textView2);
public void onButtonClick(View v){
int num1 = 0;
int num2 = 0;
int num3 = 0;
String e1 = mEditText1.getText();
String e2 = mEditText2.getText();
String e3 = mEditText3.getText();
if(!e1.isEmpty()) {
num1 = Integer.parseInt(e1);
}
if(!e2.isEmpty()){
num2 = Integer.parseInt(e2);
}
if(!e3.isEmpty()){
num3 = Integer.parseInt(e3);
}
int sub = num1 - num2 - num3;
mTextView.setText(Integer.toString(sub));
}

Change from
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
to
int num1 = 0, num2 = 0, num3 = 0;
int num1_error = 0, num2_error = 0, num3_error = 0;
try{
num1 = Integer.parseInt(e1.getText().toString());
}Catch(Exception e){
num1_error = 1;
}
try{
num2 = Integer.parseInt(e2.getText().toString());
}Catch(Exception e){
num2_error = 1;
}
try{
num3 = Integer.parseInt(e3.getText().toString());
}Catch(Exception e){
num3_error = 1;
}
// for addition
int sum = 0;
if(num1_error == 0){
sum += num1;
}
if(num2_error == 0){
sum += num2;
}
if(num1_error == 0){
sum += num3;
}
t1.setText(Integer.toString(sum));
// for subtraction
int sub = 0;
if(num1_error == 0){
sub = num1 - sub;
}
if(num2_error == 0){
sub = sub - num2;
}
if(num3_error == 0){
sub = sub - num3;
}
t1.setText(Integer.toString(sub));
// for multiplication
int mul = 1;
if(num1_error == 0){
mul = mul*num1;
}
if(num2_error == 0){
mul = mul*num2;
}
if(num3_error == 0){
mul = mul*num3;
}
t1.setText(Integer.toString(mul));

Try doing this and same for other methods:
EditText e1 ,e2, e3;
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = (EditText)findViewById(R.id.editText);
e2 = (EditText)findViewById(R.id.editText2);
e3 = (EditText)findViewById(R.id.editText3);
t1 = (TextView)findViewById(R.id.textView2);
}
public void onButtonClickSum(View v){
if(e1.getText().toString().length()==0){
e1.setError("Required");
}
else if(e2.getText().toString().length()==0){
e2.setError("Required");
}
else if(e3.getText().toString().length()==0){
e3.setError("Required");
}
else{
int num1 = Integer.parseInt(e1.getText().toString());
int num2 = Integer.parseInt(e2.getText().toString());
int num3 = Integer.parseInt(e3.getText().toString());
int sum = num1 + num2 + num3;
t1.setText(Integer.toString(sum));
}
}

Related

How do I use long Decimal Numbers in my input fields? Currently it crashes due to an improperly formatted string?

num1 and num2 are input values that need to have long decimal points but when it parses the string the decimal gets stripped and it crashes. Any assistance would be appreciated.
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button addBuyInButton = (Button) findViewById(R.id.addBuyInButton);
addBuyInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText feeNumEditText = findViewById(R.id.feeNumEditText);
EditText buyInNumEditText =
findViewById(R.id.buyInNumEditText);
TextView targetTextView = findViewById(R.id.targetTextView);
Blockquote right around here is where I run into problems...
int num1 =
Integer.parseInt(feeNumEditText.getText().toString());
int num2 =
Integer.parseInt(buyInNumEditText.getText().toString());
int num3 = 3;
int num4 = 100;
int num5 = num1 + num3;
int num6 = num5 / num4;
int num7 = num6 * num2;
int num8 = num7 + num2;
targetTextView.setText(num8 + "");
}
});
}
}
Had to use float and DecimalFormat to get desired effect.
String str2 = buyInNumEditText.getText().toString();
float num1 = Float.parseFloat(str1);
float num2 = Float.parseFloat(str2);
float num3 = 3;
float num4 = 100;
float num5 = num1 + num3;
float num6 = num5 / num4;
float num7 = num6 * num2;
float num8 = num7 + num2;
DecimalFormat formatter = new DecimalFormat("##.########");
String num9 = formatter.format(num8);

My android app is crashing due to two empty edittext fields [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Issue with empty EditText
(3 answers)
convert EditText to float - android eclipse
(6 answers)
when EditText is empty and click calculateButton, app crashes
(3 answers)
How to stop the app crashing when String is empty
(4 answers)
Closed 5 years ago.
#Override
public void onClick(View v)
{
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
}
Above is my code, when I leave any one of them empty, it crashes.How to get over it.
Just check whether user has entered anything or not and then parse your value:
if(!Total.getText().toString().matches(""))
float num1 = Float.parseFloat(Total.getText().toString());
Try Using Try...Catch
float num1 = 0.00f;
float num2 = 0.00f;
try {
num1 = Float.parseFloat(Total.getText().toString());
num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}
catch(NumberFormatException ex) {
//Handle Non Float Exception
Toast.makeText(getApplicationContext(), "Invalid input !",Toast.LENGTH_LONG).show();
}
try this
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!Total.getText().toString().trim().equals("")&&!Done.getText().toString().trim().equals("")){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});
You can apply condition if EditText is not empty then your code is run like that
float Percentage, newPercentage = 0;
int Number;
EditText Total = (EditText) findViewById(R.id.editText3);
EditText Done = (EditText) findViewById(R.id.editText4);
String total=Total.getText().toString();
String done=Done.getText().toString();
if (!total.isEmpty() && !done.isEmpty()) {
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;
}else {
Toast.makeText(OpenFile.this, "Fill values", Toast.LENGTH_SHORT).show();
}
Firstly Check whether you find editText properly or not
After that also check isEmpty condition for avoiding NullPointer Exception
if (!editText1.getText().toString().isEmpty() && !editText2.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
}
check for empty text, if not empty than perform calculation
if(!Total.getText().toString().isEmpty() && !Done.getText().toString().isEmpty()){
float num1 = Float.parseFloat(Total.getText().toString());
float num2 = Float.parseFloat(Done.getText().toString());
Percentage = (num2 / num1) * 100;}
}
});

Error while Execution android studio

I have developed an calculator app. It needs two inputs num1 and num2.
When i give the 2 inputs the arithmetic process is working good. But, when i click any buttons(add,sub,mul,division) without any inputs, the app has closed and shows the error "Unfortunately calc has stopped.
public void onButtonClick(View v){
EditText e1 = (EditText)findViewById(R.id.editText);
EditText e2 = (EditText)findViewById(R.id.editText2);
TextView t1 = (TextView)findViewById(R.id.textView);
float num1 = Integer.parseInt(e1.getText().toString());
float num2 = Integer.parseInt(e2.getText().toString());
float sum = num1 + num2; t1.setText(Float.toString(sum));
}
Just add a validation method before Onclick
private boolean validation(){
int error = 1;
if(num1.getText().toString.equals("")){error = error + 1;}
if(num2.getText().toString.equals("")){error = error + 1;}
if(error == 0){return true;} else { return false; }
}
I guess its because you're having null value in the 'editText' and you're converting null value to float without checking for the condition that it is not null.
So before conversion. check if the editText is null. Like this:
if(e1.getText().toString()!="" && e2.getText().toString()!="")
{
float num1 = Float.parseFloat(e1.getText().toString());
float num2 = Float.parseFloat(e2.getText().toString());
}
And you should use 'Float' for conversion and not 'Int'
Try this
String mNum1="",mNum2="";
mNum1=e1.getText().toString();
mNum2=e2.getText().toString();
if(!mNum1.equalsIgnoreCase("") && !mNum2.equalsIgnoreCase("") )
{
float num1 = (float) Double.parseDouble(mNum1);
float num2 = (float) Double.parseDouble(mNum2);
float sum = num1 + num2;
System.out.println("sum"+String.valueOf(sum));
t1.setText(String.valueOf(sum));
}

Android add watcher on textedit

I have the following code and i need to change a little bit the procedure. As it is it works and when i press b1 button returns me on text field et3 a calculation of 3 other text fields. I need to return the calculation on text field et3 without pressing the button. I think i need to add a watcher on text field et4 and when this is not empty then to return me the calculation on et3. The code is this
package com.example.b15_calc;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
EditText et1, et2, et3, et4;
Button b1, b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et1 = (EditText) findViewById(R.id.editText1);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
et4 = (EditText) findViewById(R.id.editText4);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
//step3 : write add functionality.
b2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
et1.setText("");
et2.setText("");
et3.setText("");
et4.setText("");
}
});
//step3 : ΜΕΤΑΒΛΗΤΕΣ
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String f = et1.getText().toString();
double i = Double.parseDouble(f);
String s = et2.getText().toString();
double j = Double.parseDouble(s);
String w = et4.getText().toString();
double q = Double.parseDouble(w);
double price_gold = 10;
double fpa = 1.23;
double fpol = 0.10;
double fpolam = 999;
double isot = 100;
double sint_ker = 10;
double result1 = (i * price_gold) + (j * 1000) + (q * isot);
double result2 = result1 / 340.75;
int gap;
if (result2 >= fpolam){
double result = (result2 * fpol);
double result3 = ((result2 * sint_ker) * fpa) + result;
if(result3 < 1000)
{
gap = 10;
}
else if(result3 < 5000)
{
gap = 50;
}
else //5000+
{
gap = 100;
}
int total = (int) Math.ceil(result3 / gap) * gap;
String res = String.valueOf(total);
et3.setText(res);
} else{
double result3 = ((result2 * sint_ker) * fpa);
if(result3 < 1000)
{
gap = 10;
}
else if(result3 < 5000)
{
gap = 50;
}
else //5000+
{
gap = 100;
}
int total = (int) Math.ceil(result3 / gap) * gap;
String res = String.valueOf(total);
et3.setText(res);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You can use TextWatcher
et4.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// make the calculation here and set the result to et3
String f = et1.getText().toString();
double i = Double.parseDouble(f);
String s = et2.getText().toString();
double j = Double.parseDouble(s);
String w = s.toString();
double q = Double.parseDouble(w);
double price_gold = 10;
double fpa = 1.23;
double fpol = 0.10;
double fpolam = 999;
double isot = 100;
double sint_ker = 10;
double result1 = (i * price_gold) + (j * 1000) + (q * isot);
double result2 = result1 / 340.75;
int gap;
if (result2 >= fpolam){
double result = (result2 * fpol);
double result3 = ((result2 * sint_ker) * fpa) + result;
if(result3 < 1000)
{
gap = 10;
}
else if(result3 < 5000)
{
gap = 50;
}
else //5000+
{
gap = 100;
}
int total = (int) Math.ceil(result3 / gap) * gap;
String res = String.valueOf(total);
et3.setText(res);
} else{
double result3 = ((result2 * sint_ker) * fpa);
if(result3 < 1000)
{
gap = 10;
}
else if(result3 < 5000)
{
gap = 50;
}
else //5000+
{
gap = 100;
}
int total = (int) Math.ceil(result3 / gap) * gap;
String res = String.valueOf(total);
et3.setText(res);
}
}
});

CalculateButton in BMI calculator

it's me again... I want to ask how to make my "button" (calculateButton) not to function if the user won't input their weight & height... or the user don't input their weight or their height... Hope you can help me... thanks..
Here is the code for my calculateButton:
public void calculateClickHandler(View view) {
if (view.getId() == R.id.calculateButton) {
}
EditText weightText = (EditText) findViewById(R.id.weightT);
EditText heightText = (EditText)findViewById(R.id.heightT);
TextView resultText = (TextView)findViewById(R.id.resultLabel);
TextView categoryText = (TextView)findViewById(R.id.categoryLabel);
rGroup = (RadioGroup)findViewById(R.id.rGroup);
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
String bmiInterpretation = interpretBMI(bmiValue);
resultText.setText("Your BMI is:" + " " + bmiValue + " " + "and you're");
categoryText.setText(bmiInterpretation + ".");}
You need to insert "validations" in your code. Basically checking the value of the string in your EditText before performing any operation.
Something like:
rGroup = (RadioGroup)findViewById(R.id.rGroup);
if( !weightText.getText().toString.equals(" ")){
int weight = (int) Float.parseFloat(weightText.getText().toString());
int height = (int) Float.parseFloat(heightText.getText().toString());
int bmiValue = calculateBMI(weight, height);
}
Refer:
Android, Validate an empty EditText field
https://sites.google.com/site/khetiyachintan/sample-example/edit-text-validation-example
Android EditText validation

Categories

Resources