How to calculate the sum of EditText boxes? - android

Hi all I am having a little trouble handling this question. I have 5 EditText boxes and I ask the user to put a number in them. Then I want to calculate the sum of the EditText boxes and do something with the sum. However I am having trouble in the case if the user don't put a number in all the boxes.
Is it possible to put a default value "0" in the boxes just in case not all the boxes are filled but the sum to be calculated although not all the boxes are filled?
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_extra_question);
textBox1 = (EditText) findViewById(R.id.editText1);
textBox2 = (EditText) findViewById(R.id.editText2);
textBox3 = (EditText) findViewById(R.id.editText3);
textBox4 = (EditText) findViewById(R.id.editText4);
textBox5 = (EditText) findViewById(R.id.editText5);
buttON = (Button) findViewById(R.id.button1);
buttON.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
number1 = Integer.parseInt(textBox1.getText().toString());
number2 = Integer.parseInt(textBox2.getText().toString());
number3 = Integer.parseInt(textBox3.getText().toString());
number4 = Integer.parseInt(textBox4.getText().toString());
number5 = Integer.parseInt(textBox5.getText().toString());
sum = number1 + number2 + number3 + number4 + number5;
if(sum > 100)
{
Toast.makeText(getApplicationContext(), "Nice!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Fail!", Toast.LENGTH_LONG).show();
}
}
});

Do this for each number:
number1 = textBox1.getText().toString().trim().isEmpty()?0:Integer.parseInt(textBox1.getText().trim().toString());

Create on function like this
public int getIntFromString(String str) {
if (str != null) {
if (str.equalsIgnoreCase("")) {
return 0;
} else {
try {
return Integer.parseInt(str);
} catch (NumberFormatException e) {
return 0;
}
}
} else {
return 0;
}
}
Then Your code should be
number1 = getIntFromString(textBox1.getText().toString().trim());
number2 = getIntFromString(textBox2.getText().toString().trim());
number3 = getIntFromString(textBox3.getText().toString().trim());
number4 = getIntFromString(textBox4.getText().toString().trim());
number5 = getIntFromString(textBox5.getText().toString().trim());

Yes your idea is correct. For each of the edit texts , just check:
if(textBox1.getText().toString().equals(""))
{
number1 = 0;
}
else
number1 = Integer.parseInt(textBox1.getText().toString());

You have to check Empty String using the below code and put "0" in every missing value.
number1 = textBox1.getText().toString().isEmpty()?0:Integer.parseInt(textBox1.getText().toString());
number2 = textBox2.getText().toString().isEmpty()?0:Integer.parseInt(textBox2.getText().toString());
number3 = textBox3.getText().toString().isEmpty()?0:Integer.parseInt(textBox3.getText().toString());
number4 = textBox4.getText().toString().isEmpty()?0:Integer.parseInt(textBox4.getText().toString());
number5 = textBox5.getText().toString().isEmpty()?0:Integer.parseInt(textBox5.getText().toString());

Related

User Input of int won't be null

I made a code where user put value between some range and my code generate random number for them. Randomization working properly but when fields are blank my app is crash how should I fix it.
randNum.java
Button generateNum = findViewById(R.id.generate_number);
generateNum.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
// if(sNum == null || fNum == null){
//
// ans.setText(getString(R.string.enterNumError));
//
// }
// else
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}
});
I try to use null but it is not working.
You need to put validation first on button click. (For checking if user has entered nothing or just spaces in any of edittexts).
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
strNum1 = edtl.getText().toString().trim();
strNum2 = edt2.getText().toString().trim();
if (strNum1.length() == 0)
{
showAlert("Please enter Num 1");
}
else if (strNum2.length() == 0)
{
showAlert("Please enter Num 2");
}
else
{
int numvalue1 = Integer.parseInt(strNum1);
int numvalue2 = Integer.parseInt(strNum2);
generateNum (numvalue1, numvalue2); //Call your function for generation of random number here
//do your stuff here
}
}
});
Hope this helps you understand the validation of forms for empty input fields.
P.S: I would recommend you put inputType attribute for your EditTexts if you have not added it already in xml file like:
android:inputType="number"
So you can avoid exception at Integer.parseInt if user enters any alphabet or symbol.
You need to handle NumberFormatException thrown by Integer.valueOf() function
try {
EditText et = findViewById(R.id.fromNum);
String sTextFromET = et.getText().toString();
int fNum = Integer.valueOf(sTextFromET);
EditText et1 = findViewById(R.id.toNum);
String sTextFromET1 = et1.getText().toString();
int sNum = Integer.valueOf(sTextFromET1);
TextView ans = findViewById(R.id.ans);
if(sNum < fNum){
ans.setText(getString(R.string.max_min_error));
}else {
final int random = new Random().nextInt((sNum - fNum) + 1) + fNum;
String ras = Integer.toString(random);
ans.setText(ras);
}
}catch(NumberFormatException e){
Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();
}

How to restrict user to input only a range of values in EditText box?

In my EditText I need the user to input data only from 5 to 10 decimal values.
How do I achieve this?
If the user enters the value less than 5 or greater than 10 I need to prompt the user to enter the value between 5 and 10.
package com.sabari.results;
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 android.widget.Toast;
public class Calculator extends AppCompatActivity {
TextView tv1;
TextView tv2;
TextView tv3;
TextView tv4;
TextView tv5;
TextView tv6;
TextView tv7;
TextView tv8;
TextView tv10;
EditText et1;
EditText et2;
EditText et3;
EditText et4;
EditText et5;
EditText et6;
EditText et7;
EditText et8;
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("CGPA Calculator");
setContentView(R.layout.calculator);
tv1 = (TextView) findViewById(R.id.textView);
tv2 = (TextView) findViewById(R.id.textView2);
tv3 = (TextView) findViewById(R.id.textView3);
tv4 = (TextView) findViewById(R.id.textView4);
tv5 = (TextView) findViewById(R.id.textView5);
tv6 = (TextView) findViewById(R.id.textView6);
tv7 = (TextView) findViewById(R.id.textView7);
tv8 = (TextView) findViewById(R.id.textView8);
b1 = (Button) findViewById(R.id.button);
b2 = (Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et1 = (EditText) findViewById(R.id.editText);
et2 = (EditText) findViewById(R.id.editText2);
et3 = (EditText) findViewById(R.id.editText3);
et4 = (EditText) findViewById(R.id.editText4);
et5 = (EditText) findViewById(R.id.editText5);
et6 = (EditText) findViewById(R.id.editText6);
et7 = (EditText) findViewById(R.id.editText7);
et8 = (EditText) findViewById(R.id.editText8);
tv10 = (TextView) findViewById(R.id.textView10);
int n;
double no1=0, no2=0, no3=0, no4=0, no5=0, no6=0, no7=0, no8=0;
try {
no1 = Double.parseDouble(et1.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try{
no2 = Double.parseDouble(et2.getText().toString());}
catch (NumberFormatException e){
e.printStackTrace();
}
try {
no3 = Double.parseDouble(et3.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try {
no4 = Double.parseDouble(et4.getText().toString());
}catch (NumberFormatException e)
{
e.printStackTrace();
}
try{
no5 = Double.parseDouble(et5.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try{
no6 = Double.parseDouble(et6.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
try {
no7 = Double.parseDouble(et7.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}try {
no8 = Double.parseDouble(et8.getText().toString());
}catch (NumberFormatException e){
e.printStackTrace();
}
if (no1<=0) {
n = 1;
} else if (no3<=0||et3.equals("")) {
n = 2;
} else if (no4<=0||et4.equals("")) {
n = 3;
} else if (no5<=0||et5.equals("")) {
n = 4;
} else if (no6<=0||et6.equals("")) {
n = 5;
} else if (no7<=0||et7.equals("")) {
n = 6;
} else if (no8<=0||et8.equals("")) {
n = 7;
} else {
n = 8;
}
double res = 0;
if((no1<=10)&&(no2<=10)&&(no3<=10)&&(no4<=10)&&(no5<=10)&&(no6<=10)&&(no7<=10)&&(no8<=10)) {
res = (no1 + no2 + no3 + no4 + no5 + no6 + no7 + no8) / n;
tv10.setText("Your CGPA is : " + res);
Toast.makeText(Calculator.this, "Your CGPA is : " + res, Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Calculator.this,"Please enter a valid GPA ",Toast.LENGTH_LONG).show();
}
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
et2.setText("");
et3.setText("");
et4.setText("");
et5.setText("");
et6.setText("");
et7.setText("");
et8.setText("");
tv10.setText("Your CGPA is : ");
et1.setText("");
}
});
}
}
After you parse the double they entered, you can do an easy if statement to check if the value they entered is between 5 and 10:
if (no1 < 5 || no1 > 10)
{
// error... prompt them to enter value between 5 and 10
}
Alternatively, you can check for a correct value like so:
if (no1 >= 5 && no1 <= 10)
{
// good value
}
Also, to only allow the user to enter a float value, you can set the inputType property of your EditTexts to numberDecimal:
<EditText
...
android:inputType="numberDecimal"
... />
You can use an AlertDialog to let the user know the value they entered is incorrect.
As for your entire setup, you could make the code look a lot cleaner if you put all the EditTexts into a List/array, and all of the double values into another List. (A dictionary relating the two values would also be a good option). With this setup, your big section of 8 try-catch blocks would be reduced to:
for (int i = 0; i < editTexts.Length; i++)
{
try
{
nums[i] = Double.parseDouble(editTexts[i].getText().toString());
}
catch (NumberFormatException e)
{
e.printStackTrace();
}
}
Your block for checking if the values are between 5 and 10 would look similar, and you could have a Boolean value indicating whether or not an invalid value was found. The loop would break when one was found:
Boolean invalidFound = false;
for (int i = 0; i < nums.Length && !invalidFound; i++)
{
invalidFound = (nums[i] < 5 || nums[i] > 10);
}
if (invalidFound)
{
//error
}
else
{
// good values
}
There are many ways to set this up. Some of the other options might be cleaner, but I wanted to show you an option that was relatively easier to understand.

What's wrong with my code ? everytime I click the app crashes

I'm working on a simple calculator
I'm still a beginner and don't know much about java or android
however, everytime I click on the button the app crashes!
what's wrong with the code ?
final Button btn = (Button) findViewById(R.id.btn);
final EditText ET = (EditText) findViewById(R.id.ET);
final EditText ET2 = (EditText) findViewById(R.id.ET2);
final EditText ET3 = (EditText) findViewById(R.id.ET3);
final TextView TV = (TextView) findViewById(R.id.textView4);
final TextView TV2 = (TextView) findViewById(R.id.textView5);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String et = ET.getText().toString();
String et2 = ET2.getText().toString();
String et3 = ET3.getText().toString();
for (int i = Integer.parseInt(et2); i < Integer.parseInt(et3); i++) {
try {
str = et.replace("X", "" + i);
}
catch (Exception e) {
str = et.replace("x", "" + i);
}
int rslt = Integer.parseInt(str);
TV.append( " " + i )
TV2.append( " " + rslt )
}
}
}
});
That's all codes already
this code is meant to make a table for a F(X) method like the one on the casio calculator. I may need it for school
like :
F(X) = X^2 + X*4 - 3
One problem I see is that outer try misses corresponding catch block and you do not check whether proper number is entered in Et2 and Et3. Integer.parseInt will throw an exception if provided text is not a proper number.

sharedPreference or onSaveInstanceState on an EditText/TextView result

I have a little test project below. All I want to do is save the EditText numbers entered and TextView result (thing1, thing2, result) . What's best? onSaveInstanceState, sharedPreference, or something different like SQLite?
I've frustratingly tried the first two (for probably embarrassingly too long), but couldn't figure it out. Could someone please help by adding it to the code below?
public class MainActivity extends ActionBarActivity {
EditText thing1;
EditText thing2;
TextView result;
double n1=0;
double n2=0;
double total=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button divideButton = (Button) findViewById(R.id.divideButton);
divideButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
if (n2 !=0){
total = (n1 / n2);}
final double total = ((double)n1/(double)n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1+n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button subtractButton = (Button) findViewById(R.id.subtractButton);
subtractButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1-n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
final Button multiplyButton = (Button) findViewById(R.id.multiplyButton);
multiplyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
thing1 = (EditText) findViewById(R.id.thing1);
if (TextUtils.isEmpty(thing1.getText().toString())) {
n1 = 0;}
else {
n1= Double.parseDouble(thing1.getText().toString());
}
thing2 = (EditText) findViewById(R.id.thing2);
if (TextUtils.isEmpty(thing2.getText().toString())) {
n2 = 0;}
else {
n2 = Double.parseDouble(thing2.getText().toString());
}
final double total = (n1*n2);
final TextView result= (TextView) findViewById(R.id.result);
String foo = String.format("%.2f", total);
result.setText(foo);
}
});
}
If you will just use the values later like when you open your application, you
can use the SharedPreferences. Based on your code above you can add the code below
to save your EditText data to SharedPreferences and restore it later.
To save your EditText value:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("thing1", thing1.getText.toString());
editor.commit();
To get the value from SharedPreferences you can do this in your onCreate function:
SharedPreferences sharedPreferences = getApplication().getSharedPreferences("ProjectName", MODE_PRIVATE);
String sValue = sharedPreferences.getString("thing1", "default");
thing1.setText( sValue );

Unfortunately android app has stopped

I am doing a simple program for addition of two numbers which are input from EditText.
But when user clicks the button 'Click to Add' leaving the fields empty, program exits saying 'Unfortunately, program has stopped.'
Here is the code:
public class MainActivity extends Activity {
long a, b, sum;
Button add, clr;
EditText e1, e2, res;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
add = (Button) findViewById(R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1 = (EditText) findViewById(R.id.tv1);
String str1 = e1.getText().toString();
e2 = (EditText) findViewById(R.id.tv2);
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
});
clr = (Button) findViewById(R.id.bClr);
clr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1.setText("");
e2.setText("");
res.setText("");
}
});
}
}
I want the app to respond 'Please enter valid entries' for blank EditText entries.
Your line:
res = (EditText) findViewById(R.id.result);
must be moved so that your res variable is initialized before you use res.setText. It's not initialized in your catch statement.
Move it to the position indicated below. You can initialise it when you do your other findViewById
e1 = (EditText) findViewById(R.id.tv1);
e2 = (EditText) findViewById(R.id.tv2);
res = (EditText) findViewById(R.id.result);
because you are getting a null text from the edit texts..so check for null first
#Override
public void onClick(View v) throws NumberFormatException {
// TODO Auto-generated method stub
e1 = (EditText) findViewById(R.id.tv1);
e2 = (EditText) findViewById(R.id.tv2);
if( e1.getText() != null && e2.getText() != null) {
String str1 = e1.getText().toString();
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
}
Yes.
Add these lines.
if (e1.getText().toString() == null || e2.getText().toString() == null)
{
//Show dialog
}
else
{
String str1 = e1.getText().toString();
String str2 = e2.getText().toString();
try{
a = Integer.parseInt(str1);
b = Integer.parseInt(str2);
}catch(NumberFormatException e){
res.setText("Please enter valid entries");
}
sum = a + b;
res = (EditText) findViewById(R.id.result);
res.setText("Your sum is " + sum);
}
}
And tutorial for any help on alert dialog
Instead of catching NumberFormatException you can just catch any Exception in try catch block .Please post the Log Cat Error you are getting.

Categories

Resources