EditText crashing simple calculator - android

I'm trying to build basic calculator, but when I put a number at first edittext and hit add button, it gets crashed.
It is fine when I add two number in both editTexts. There was no problem in that. But the problem happened when I put only one number and hit add.
It is throwing NumberFormatException: Invalid int: "".
here is my basic code.
public class MainActivity extends AppCompatActivity {
EditText num1;
EditText num2;
Button add,sub,multi,div;
TextView MyResults;
String Number1 ;//;
String Number2 ;//
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
num1 = (EditText)findViewById(R.id.num1);
num2 = (EditText)findViewById(R.id.num2);
add = (Button)findViewById(R.id.Add);
sub = (Button)findViewById(R.id.Sub);
multi = (Button)findViewById(R.id.Multiple);
div = (Button)findViewById(R.id.Divide);
MyResults = (TextView)findViewById(R.id.results);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
int myAdd = mAdd1+mAdd2;
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
}
});
}//end OnCreate.

When you leave an EditText empty
int mAdd2 = Integer.valueOf(Number2);
Will crash because a empty String is not a valid Integer (hence the NumberFormatException).
You could put it in a try/catch like this:
try {
Number1 =num1.getText().toString();
Number2 =num2.getText().toString();
int mAdd1 = Integer.valueOf(Number1);
int mAdd2 = Integer.valueOf(Number2);
MyResults.setText(String.valueOf(myAdd));
Toast.makeText(getApplicationContext(), "Added: "+ myAdd, Toast.LENGTH_LONG).show();
catch (NumberFormatException e) {
//Give a toast saying the user did not enter two correct values
}
Or alternatively, check the value beforehand and check if nothing was entered:
number1 =num1.getText().toString();
number2 =num2.getText().toString();
if (number1.equals("") || number2.equals("")) {
//Show error or set numbers to a different value
}
However, for this to work you must assume the user did not enter anything that isn't a valid Integer like a letter, for example by setting the EditText's input type to numbers.
android:inputType="number"

You should do validation checking for a blank edit text and not do the calculation in this case.
Instead you might take advantage of EditText's setError(CharSequence) method where you can show a message to the user why the input is not valid.

Related

how to I prevent a value greater than 20 inside the edittext and if the edittext is empty, write 0 inside the edittext

I want to make a quizscore calculating app. I have some problems. How to I prevent entering value greater than 20 inside the edittext and if the edittext is empty, write 0 inside the edittext and calculate the 0 value. When the application runs, it calculates the score, but when the Edittext is entered null, the application closes. I want to if edittext is null, app sets the null value 0 and calculate score.
Here's the image my app:1: https://i.stack.imgur.com/efn9H.png
Here's the code I'm using:
public class MainActivity extends AppCompatActivity {
EditText editText1,editText2,editText3;
private Button calculate;
TextView textView1;
double c=0.0,x;
int a=0,b=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1=findViewById(R.id.correct_answer);
editText2=findViewById(R.id.false_answer);
editText3=findViewById(R.id.turnet);
textView1=findViewById(R.id.hesap);
calculate=findViewById(R.id.calculate);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
x=a+b;
if (x<=20){
if (editText1.getText().toString().length()==0)
{
a=0;
Toast.makeText(getApplicationContext(),"Correct Answers must be max:20 .", Toast.LENGTH_LONG).show();
}
else{
a=Integer.parseInt(editText1.getText().toString());
}
if (editText2.getText().toString().length()==0)
{
Toast.makeText(getApplicationContext(),"False Answers must be max:20.", Toast.LENGTH_LONG).show();
b=0;
editText2.setText(0);
}
double c = a - (b / 3);
double result=((200.004394)+(c*3.44603333));
editText3.setText(Double.toString(c));
textView1.setText("Your Score: "+ Double.toString(result));
}
else{
Toast.makeText(getApplicationContext(),"All English questions dont greater than 20.", Toast.LENGTH_LONG).show();
}
};});}}
There is a problem with this code :
a=Integer.parseInt(editText1.getText().toString());
b=Integer.parseInt(editText2.getText().toString());
when one of your edittextes is empty, then an error will be thrown because Integer.parseInt cannot accept an empty string.
so use this:
a = 0;
b = 0;
if (editText1.getText().toString() != ""){
a=Integer.parseInt(editText1.getText().toString());
}
if(editText2.getText().toString() != ""){
b=Integer.parseInt(editText2.getText().toString());
}
x = a + b
You can use TextWatcher. Write a TextWatcher which change value to 20 if it is greater than 20 or set it to 0 if EditText's text becomes empty

Android - How to calculate one edit text and divide another value?

I am a total beginner, I am wondering if anyone could help me out with the code. I am trying to make ideal daily water intake apps.
There will be only one edit text for user to input their weight and I want it to divide for example 0.024. Have button to calculate and then display the answer on screen.
public class WaterCalculate extends Activity {
//Declare textviews as fields, so they can be accessed throughout the activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
//Bind the EditText views
weightuser = (EditText)findViewById(R.id.weight);
tv4 = (TextView)findViewById(R.id.res);
calculate = (ImageButton)findViewById(R.id.calc);
calculate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
//get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
//do the calculation
Double calculatedValue = (value1/0.024);
//set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
}
}
When i run the apps the button to calculate its not working and it show the app has stopped. Appreciate for the help.
I thought the problem is in this line.
tv4.setText(String.valueOf("You need " + calculatedValue + "\nliters of water per day" ));
Give a try like this...
tv4.setText("You need "+Double.toString(calculatedValue)+"\nliters of water per day");
and also ensure that you catched the exceptions at necessary places like converting editText value into double.
Try the below code, am sure it will work, when you use click listener for button you should use View.Onclick
class WaterCalculate extends Activity {
// Declare textviews as fields, so they can be accessed throughout the
// activity.
EditText weightuser;
TextView tv4;
ImageButton calculate;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.water_calculate);
// Bind the EditText views
weightuser = (EditText) findViewById(R.id.weight);
tv4 = (TextView) findViewById(R.id.res);
calculate = (ImageButton) findViewById(R.id.calc);
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calculate();
}
});
}
private void calculate() {
// get entered texts from the edittexts,and convert to integers.
Double value1 = Double.parseDouble(weightuser.getText().toString());
// do the calculation
Double calculatedValue = (value1 / 0.024);
// set the value to the textview, to display on screen.
tv4.setText(String.valueOf("You need " + calculatedValue
+ "\nliters of water per day"));
}
}

Why the conversion of EditText to String was not suceesful within OnCreate method

public class MainActivity extends Activity {
EditText number1, number2;
String number_1, number_2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
After running the application, why does number_1 have an empty value.
onCreate method is create view.
So EditText number1, nubmer2 is not create yet.
If you want get number1 or number2's value, try in onPause().
Try this..
You have to get the text in like OnClick while starting application both EditText is empty. So that it returns empty.
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
Make sure you have predefined the value in the edittext and that should work
i need to see your xml.... if your trying to get numbers you have to parse the string to an int anyway... what are you trying to achieve? you simply want the text, from each of the textviews? is there text set in the xml?
Make sure you have predefined the value in the edittext in xml file.
like in your layout file android:text="your string" or else you have to set string after binding
oncreate method like.
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
number1.setText("your string");
then you have to get string from below code.
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
You need to fill the EditTexts with something before you can get their value. So create a button, and after filling the EditTexts, then get their values by clicking the button.
Perhaps like this:
public class MainActivity extends Activity {
EditText number1, number2;
String number_1, number_2;
Button submit;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = (EditText) findViewById(R.id.number1);
number2 = (EditText) findViewById(R.id.number2);
submit = (Button)findViewById(R.id.btn1); //Define a button in your layout xml file with the ID field set as "btn1"
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
number_1 = number1.getText().toString();
number_2 = number2.getText().toString();
}
});

Android:Got NumberFormatExxception while getting data from EditText field

java.lang.RuntimeException: Unable to start activity ComponentInfo { com.project/com.project.simple} : java.lang.NumberFormatException
EditText et1,et2,et3;
Button b1, b2;
Float two,three,four;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.can);
et1 = (EditText) findViewById(R.id.editText1);
two = Float.valueOf(et1.getText().toString());
et2 = (EditText) findViewById(R.id.editText2);
three = Float.valueOf(et2.getText().toString());
et3 = (EditText) findViewById(R.id.editText3);
four = Float.valueOf(et3.getText().toString());
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b1.setOnClickListener(new OnClickListener() {
you are in onCreate() where the fields are specified. the user could not have time to enter any valid data. you need to move the fetching of the data somewhere else...like your onClick() perhaps.
move your code from onCerate to an other method
(for example the onClick method of the Button )
and you should
try this:
try{
two = Float.parseFloat(et1.getText().toString());
}catch(NumberFormatException e){
two = 0;
Toast toast = Toast.makeText(this, 'Invalid number format on `two` field', 500);
toast.show();
}
For each text fields what you want to read
Comment:
float format is 2.3 and don't use 2,3
It seems that the input is not valid. Please check twice that you don't try to parse a letters to a number. If you have a float please check that you use the right locale for parsing. E.g. in germany is pi 3,1415... and not 3.1415...
If you cannot preparse the values you could put the parsing trys in try catch blocks like this:
float value;
try {
value=Float.parseFloat(someString);
} catch(NumberFormatException e) {
// input was no valid float
}

how to take input from user in android

i have a EditText in android in which i want the user to enter the text and checks for the condition "BYE"
Code sample:
EditText text = (EditText)findViewById(R.id.EditText01);
String abc= text .getText().toString();
while( !(abc).equals("bye")){
abc = text.getText().toString();//user should enter the text from keyboard and the while loop should go and chech the condition.but not able to enter the text
//do some operation with abc
}
How can i make user to enter the text??The UI should wait for the text to be entered(something like we have InputStreamReader in java applications).
Very Simple:-
EditText text = (EditText)findViewById(R.id.EditText01);
String str = text.getText().toString();
now in str u will get string which is entered in EditText
I don't think you need a loop to do this. From your comment it looks like you also have an "Enter" button or something that you click to do the checking. Just set an onclicklistener and onclick you can make the edittext invisible (or un-editable), check is the edittext is equal to "BYE" and then do your actions might look something like this:
final EditText ET = (EditText) findViewById(R.id.EnterText);
Button B1 = (Button) findViewById(R.id.EnterButton);
B1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ET.setVisibility(View.INVISIBLE);
if(ET.getText().toString() == "BYE")
{
//do something if it is "BYE"
} else {
Context context = getApplicationContext();
CharSequence text = "Please enter BYE";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
ET.setVisibility(View.VISIBLE);
} });
Instead of running this check in an infinite loop, only run it on every onKeyUp of the EditText. You know, anyway, that the condition will only ever be fulfilled if the user actually enters something.

Categories

Resources