I am designing a basic BMI calculator and I have the calculator working, but I need to convert the calculated answer from a TextView which is a double to an integer to enable me right statements with <> operators based on the calculated answer.
How do I convert the answer from the TextView to an integer?
v.findViewById(R.id.bmi).setOnClickListener(this);
return v;
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.bmi:
try {
EditText w = (EditText) getView().findViewById(R.id.w);
String value = w.getText().toString();
EditText h = (EditText) getView().findViewById(R.id.h);
String value1 = h.getText().toString();
TextView ans = (TextView) getView().findViewById(R.id.ans);
Double l1 = Double.parseDouble(value);
Double l2 = Double.parseDouble(value1);
ans.setText(Double.toString(l1 / (l2 * l2)));
}
catch (Exception e)
{
new AlertDialog.Builder(getActivity()).setNeutralButton("OK",null).setMessage("ALL FIELDS ARE REQUIRED TO COMPUTE YOUR BMI! ").show();
break;
}
}
}
}
First, The conversion is NOT from textview to int. textView aint a datatype. If you want the result in int use parseInt() method. int i = Integer.parseInt(value).
[EDIT]
Try this, this will work.
TextView tv = (TextView) findViewById(R.id.tv);
EditText et = (EditText) findViewById(R.id.et);
try {
double d = Double.valueOf(String.valueOf(et.getText()));
tv.setText(String.valueOf( (int) d));
}catch (NumberFormatException e){
Toast.makeText(MainActivity.this, "Enter valid number.", Toast.LENGTH_SHORT).show();
}
I have simplified it for your understanding. The code can still be optimized.
Related
I am trying to set an easy app that taken two numbers gives the sum of hose two. I found something about how to do this but as I try to convert string to int the app crashes. Can you help me?
Here's my method:
public void do_sum(View v)
{
EditText t1 = (EditText) findViewById(R.id.number1);
EditText t2 = (EditText) findViewById(R.id.button);
String s1 = t1.getText().toString();
String s2 = t2.getText().toString();
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int res = n1+n2;
((EditText) findViewById(R.id.result)).setText(String.valueOf(res));
}
Please can you help me?
There is a small error in your code, you should use R.id.number2 instead of R.id.button when getting the second number from the EditText view:
EditText t1 = (EditText) findViewById(R.id.number1);
EditText t2 = (EditText) findViewById(R.id.number2);
Additionally, to avoid crashing the app, you can add a try-catch block to catch the NumberFormatException that might be thrown if the strings in s1 and s2 cannot be parsed into integers:
try {
int n1 = Integer.parseInt(s1);
int n2 = Integer.parseInt(s2);
int res = n1 + n2;
((EditText) findViewById(R.id.result)).setText(String.valueOf(res));
} catch (NumberFormatException e) {
// Handle the exception here
}
I've just started off learning Adroid studio and coding with Java. I'm not sure why my if statement returns a value of 0(The initialized value).
The code above the onclicklistener works fine.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thecart);
Intent caller = getIntent();
String item = caller.getStringExtra("choice");
TextView disptext = (TextView) findViewById(R.id.carttoptext);
disptext.setText("You selected " + item);
EditText quantity = (EditText) findViewById(R.id.inputquantity);
Button calc= (Button) findViewById(R.id.calc);
calc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double price=0;
double vquant = valueOf(quantity.getText().toString());
String item = caller.getStringExtra("choice");
if (item.equals("Eggs")) {
price = vquant * 4;
} else if (item.equals("Milk")) {
price = vquant * 30;
} else if (item.equals("Bread")) {
price = vquant * 23;
} else if (item.equals("Chips")) {
price = vquant * 20;
} else if (item.equals("Maggi")) {
price = vquant * 15;
}
DecimalFormat formatval = new DecimalFormat("##.##");
TextView pricetext = (TextView) findViewById(R.id.pricetext);
pricetext.setText("Total: " + formatval.format(price));
}
});
}
}
I'm expecting the textview beneath the edittext to give me the value vquant*(if condition value). But I'm getting the Textview as Total: 0 , which is the initializing value.
What changes should I make to the code so that I get desired output?
check if the vquant is able to fetch the value from the quantity as a double.
ValueOf() change the data into String and you are taking that data to a double variable. It won't work. Use Double.valueOf()
Have you tried "Double.parseDouble(..)" instead of valueOf?
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.
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.
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());