How to stop the app crashing when String is empty - java

The app crash when there is no text !
I don't have what 'if' to put to fix that !
Thanks you
enter TextView TotalTextView;
EditText EnterPercentage;
EditText EnterPrice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TotalTextView = (TextView) findViewById(R.id.TotalTextView);
EnterPercentage = (EditText) findViewById(R.id.EnterPercentage);
EnterPrice = (EditText) findViewById(R.id.EnterPrice);
Button CalcBtn = (Button) findViewById(R.id.CalcBtn);
CalcBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
}
});
Thank for your answer, I am a begineer so... Thanks !
if (EnterPercentage.getText().equals("")) {
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
} else {
}
the button don't do anything but the app doesn't crash

We check the length of the String... when it's 0 then we do nothing. When the String > 0 your code is running.
Like:
if (EnterPercentage.getText().trim().toString().length() == 0 || EnterPrice.getText().toString().length() == 0 ) {
//Textfields are empty.
Log.d("Error","Fields are empty");
} else {
//Textfield is full
float percentage = Float.parseFloat(EnterPercentage.getText().toString());
float prix = Float.parseFloat(EnterPrice.getText().toString());
float dec = percentage / 100;
float total = prix - dec * Float.parseFloat(EnterPrice.getText().toString());
TotalTextView.setText(String.format("%.2f", total));
}

You need to check (obviously) your string. The if that your code is missing is :
if (TextUtils.isEmpty(EnterPercentage.getText()) || TextUtils.isEmpty(EnterPrice.getText())) {
// YOUR CODE
}
Good luck with android development.
Questions was already posted

You surely got a NullPointerException. That's because the text is null and you put a .toString() after.
Try this:
float percenteage = 0;
float prix = 0;
if (EnterPercentage.getText() != null)
percenteage = Float.parseFloat(EnterPercentage.getText().toString());
if (EnterPrice.getText() != null)
prix = Float.parseFloat(EnterPercentage.getText().toString());

you need to validate before trying to convert to float
float percentage = getFloat();
private float getFloat(){
float fRet = 0.0f;
if(your validation here){
fRet = Float.parseFloat(EnterPercentage.getText().toString());;
}
return fRet;
}

Related

Rounding results from different java calculations

So I've got the following code which makes some calculations depending on user input and then shows the results in a textView.
public class DescentCalculator extends AppCompatActivity {
EditText num1, num2, num3;
TextView resu;
double startdecent;
double feetminute;
#Override
public void onCreate ( Bundle savedInstanceState ) {
super.onCreate(savedInstanceState);
setContentView(R.layout.descent);
Toolbar mToolbar = (Toolbar) findViewById(R.id.mtoolbar);
setSupportActionBar(mToolbar);
Button add = (Button) findViewById(R.id.button11);
num1 = (EditText) findViewById(R.id.altitude_fix);
num2 = (EditText) findViewById(R.id.altitude_cruise);
num3 = (EditText) findViewById(R.id.mach_speed);
resu = (TextView) findViewById(R.id.answer);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick ( View v ) {
// TODO Auto-generated method stub
String altfix = num1.getText().toString();
String altcruise = num2.getText().toString();
String machspeed = num3.getText().toString();
startdecent = (Double.parseDouble(altcruise) - Double.parseDouble(altfix)) / 100 / 3;
feetminute = (3 * Double.parseDouble(machspeed) * 1000);
resu.setText(Double.toString(startdecent) + Double.toString(feetminute));
}
});
}
For example, if the user enters 7000 for the altcruise, 6000 for altfix and 0.30 for machspeed the app calculates the answer as 3.33333333333335899.999999999 which is technically right. I'd like the app to round up the answer and display 3.3 in this case.
Look at this answer: Round a double to 2 decimal places
This code snippet takes in a double and reads it into a BigDecimal and rounds it returning a double with n decimalplaces.
public static void main(String[] args){
double myDouble = 3.2314112;
System.out.print(round(n,1));
}
public static double round(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
This returns 3.2

Converting to Float for Math Operations

Writing a program in Android Studio 2.2.2 (MainActivity.java). Basically there are multiple inputs, one button, multiple outputs. However, many of the outputs are cross referenced into many of the other outputs. I'm new to all of this as our professor threw this on us in a non-programming class. Can anyone see some of my errors? I hope that I'm doing the process mostly correct, but the operations are all have issues with string/float/double incompatibilities. Thanks for any insight!
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnCalc;
private TextView tvaResult;
private TextView tvcResult;
private TextView tvetResult;
private TextView tvphiResult;
private TextView tvMnResult;
private TextView tvphiMnResult;
private TextView tvbeta1Result;
private EditText etB,etD,etH,etAs,etFc,etFy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
btnCalc = (Button)findViewById(R.id.btnCalc);
etB = (EditText)findViewById(R.id.etB);
etD = (EditText)findViewById(R.id.etD);
etH = (EditText)findViewById(R.id.etH);
etAs = (EditText)findViewById(R.id.etAs);
etFc = (EditText)findViewById(R.id.etFc);
etFy = (EditText)findViewById(R.id.etFy);
tvaResult = (TextView)findViewById(R.id.tvaResult);
tvcResult = (TextView)findViewById(R.id.tvcResult);
tvetResult = (TextView)findViewById(R.id.tvetResult);
tvphiResult = (TextView)findViewById(R.id.tvphiResult);
tvMnResult = (TextView)findViewById(R.id.tvMnResult);
tvphiMnResult = (TextView)findViewById(R.id.tvphiMnResult);
tvbeta1Result = (TextView)findViewById(R.id.tvbeta1Result);
btnCalc.setOnClickListener(this);
}
#Override
public void onClick(View view) {
Float B = Float.parseFloat(etB.getText().toString());
Float D = Float.parseFloat(etD.getText().toString());
Float H = Float.parseFloat(etH.getText().toString());
Float As = Float.parseFloat(etAs.getText().toString());
Float Fc = Float.parseFloat(etFc.getText().toString());
Float Fy = Float.parseFloat(etFy.getText().toString());
Float aResult = Float.parseFloat(tvaResult.getText().toString());
Float cResult = Float.parseFloat(tvcResult.getText().toString());
Float etResult = Float.parseFloat(tvetResult.getText().toString());
Float beta1Result = Float.parseFloat(tvbeta1Result.getText().toString());
Float phiResult = Float.parseFloat(tvphiResult.getText().toString());
switch(view.getId() ) {
case R.id.btnCalc:
tvaResult = (Fy * As) / (0.85 * Fc * B);
tvcResult = aResult / beta1Result;
tvetResult = ((D - cResult) / (cResult)) * 0.003;
if (Fc <= 4000) {
beta1Result = 0.85;
} else if (4000 < Fc <= 8000) {
beta1Result= ((0.85)-(0.05 * ((Fc - 4000) / (1000))));
} else {
beta1Result= 0.65;
}
if (etResult >= 0.005) {
tvphiResult= 0.9;
} else if (0.002 <= etResult < 0.005) {
tvphiResult= 0.65 + ((etResult - 0.002) * ((0.25) / (0.005 - 0.002)));
} else {
tvphiResult= 0.00
}
tvMnResult= (Fy * As) * (etD - (aResult / 2));
tvphiMnResult= phiResult * tvMnResult
}}
}}
To make it short, you need to keep the type of each Variable.
Here for example :
tvaResult = (Fy * As) / (0.85 * Fc * B);
You have
TextView = (Float * Float) / ( Double * Float * Float)
TextView = Double // Not possible
You are trying to put a Float value into a Instance of TextView, this can't be done of course. But you really want to update the text of the Textview, so use the methods setText(String) of TextView like :
tvaResult.setText((Fy * As) / (0.85 * Fc * B) + ""); // Need to be convert into String
To change the text to print
This is basicly always the same mistake done, you need to change the text of the TextView an not trying to change the instance itself.

Why are my Java percentages slightly wrong?

I'm writing a simple Percentage Calculator android app in Android Studio. Here's my psuedo:
resultView = (TextView) findViewById(R.id.ResultView);
percentageText = (EditText) findViewById(R.id.PercentageInput);
numberText = (EditText) findViewById(R.id.NumberInput);
Button calcButton = (Button) findViewById(R.id.Calculate_btn);
calcButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
if(percentageText.length() != 0 && numberText.length() != 0)
{
float percentage = Float.parseFloat(percentageText.getText().toString()) / 100;
float result = percentage * Float.parseFloat(numberText.getText().toString());
resultView.setText(Float.toString(result));
}
else if(percentageText.length() == 0 && numberText.length() == 0)
{
resultView.setText("Don't be dumb...");
}
}
});
so it seemed like everything was working fine. Simple percentages are always right. 50%100=50, 25%50=12.5 ... but then I get to 3 and 6. 3%10= 0.29999998 ... shouldn't it be .3? and 60%100= 60.000004 ... Any help out there?
It has to do with the fact that double variables have a limited number of bits. This is like saying 1/3 = 0.33333333 when really is should be equal to 0.33333333... forever!
Read about Floating points and Double precision

Calling the appropriate function

I'm new to android development and having a hard time trying to call the appropriate function on my setOnClickListener, I have 3 function each have a set of editText that the user can input some double values this values are then return by the function and when the user clicks calculate displays the right information, however, I'm trying to check if there's a value either in the editText or the function so I can display the right information, but I can't figure it out.
1 function at a time works
public class MainWindowActivity extends AppCompatActivity {
private Button calculateButton;
private EditText length1Text;
private EditText length2Text;
private EditText length3Text;
private EditText width1Text;
private EditText width2Text;
private EditText width3Text;
private EditText thick1Text;
private EditText thick2Text;
private EditText thick3Text;
private EditText squareYards1Text;
private EditText squareYards2Text;
private EditText squareYards3Text;
private EditText result1TotalText;
private EditText result2TotalText;
private EditText result3TotalText;
private EditText grandTotalText;
private Double length1 = 0.0;
private Double length2 = 0.0;
private Double length3 = 0.0;
private Double width1 = 0.0;
private Double width2 = 0.0;
private Double width3 = 0.0;
private Double thick1 = 0.0;
private Double thick2 = 0.0;
private Double thick3 = 0.0;
private Double syard1 = 0.0;
private Double syard2 = 0.0;
private Double syard3 = 0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_window);
calculateButton = (Button) findViewById(R.id.calculateButtonPressed);
calculateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(CalculateArea1() == null){
CalculateArea2();
CalculateArea3();
Total = CalculateArea2() + CalculateArea3();
}
grandTotalText.setText(String.format("%.1f",Total));
}
});
public Double CalculateArea1(){
length1Text = (EditText) findViewById(R.id.length1Text);
width1Text = (EditText) findViewById(R.id.width1Text);
thick1Text = (EditText) findViewById(R.id.thickness1Text);
squareYards1Text = (EditText) findViewById(R.id.squareYards1Text);
result1TotalText = (EditText) findViewById(R.id.result1TotalText);
grandTotalText = (EditText) findViewById(R.id.grandTotalText);
if (squareYards1Text.getText().toString().trim().length() == 0) {
length1 = Double.valueOf(length1Text.getText().toString());
width1 = Double.valueOf(width1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
}else{
syard1 = Double.valueOf(squareYards1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
}
//area 1
double yard = length1 * width1 / 9;
double t = yard / thick1;
double y1 = 12.20 / thick1;
double sy1 = syard1 / y1;
if (thick1 == 1) {
t = yard / 12.20;
}else if(thick1 == 1.25){
t = yard / 9.76;
}else if (thick1 == 1.5){
t = yard / 8.13;
}else if (thick1 == 1.75){
t = yard / 6.97;
}else if (thick1 == 2){
t = yard / 6.1;
}
Double result;
if (length1Text.getText().toString().trim().length() == 0) {
result1TotalText.setText(String.format("%.1f", sy1));
grandTotalText.setText(String.format("%.1f", sy1));
result = sy1;
} else {
result1TotalText.setText(String.format("%.1f", t));
squareYards1Text.setText(String.format("%.1f", yard));
grandTotalText.setText(String.format("%.1f", t));
result = t;
}
return result;
}
public Double CalculateArea2(){
length2Text = (EditText) findViewById(R.id.length2Text);
width2Text = (EditText) findViewById(R.id.width2Text);
thick2Text = (EditText) findViewById(R.id.thickness2Text);
squareYards2Text = (EditText) findViewById(R.id.squareYards2Text);
result2TotalText = (EditText) findViewById(R.id.result2TotalText);
grandTotalText = (EditText) findViewById(R.id.grandTotalText);
if (squareYards2Text.getText().toString().trim().length() == 0) {
length2 = Double.valueOf(length2Text.getText().toString());
width2 = Double.valueOf(width2Text.getText().toString());
thick2 = Double.valueOf(thick2Text.getText().toString());
}else{
syard2 = Double.valueOf(squareYards2Text.getText().toString());
thick2 = Double.valueOf(thick2Text.getText().toString());
}
//area 2
double yard2 = length2 * width2 / 9;
double t2 = yard2 / thick2;
double y2 = 12.20 / thick2;
double sy2 = syard2 / y2;
if (thick2 == 1) {
t2 = yard2 / 12.20;
}else if(thick2 == 1.25){
t2 = yard2 / 9.76;
}else if (thick2 == 1.5){
t2 = yard2 / 8.13;
}else if (thick2 == 1.75){
t2 = yard2 / 6.97;
}else if (thick2 == 2){
t2 = yard2 / 6.1;
}
Double result;
if (length2Text.getText().toString().trim().length() == 0) {
result2TotalText.setText(String.format("%.1f", sy2));
grandTotalText.setText(String.format("%.1f", sy2));
result = sy2;
} else {
result2TotalText.setText(String.format("%.1f", t2));
squareYards2Text.setText(String.format("%.1f", yard2));
grandTotalText.setText(String.format("%.1f", t2));
result = t2;
}
return result;
}
public Double CalculateArea3(){
length3Text = (EditText) findViewById(R.id.length3Text);
width3Text = (EditText) findViewById(R.id.width3Text);
thick3Text = (EditText) findViewById(R.id.thickness3Text);
squareYards3Text = (EditText) findViewById(R.id.squareYards3Text);
result3TotalText = (EditText) findViewById(R.id.result3TotalText);
grandTotalText = (EditText) findViewById(R.id.grandTotalText);
if (squareYards3Text.getText().toString().trim().length() == 0) {
length3 = Double.valueOf(length3Text.getText().toString());
width3 = Double.valueOf(width3Text.getText().toString());
thick3 = Double.valueOf(thick3Text.getText().toString());
}else{
syard3 = Double.valueOf(squareYards3Text.getText().toString());
thick3 = Double.valueOf(thick3Text.getText().toString());
}
//area 3
double yard3 = length3 * width3 / 9;
double t3 = yard3 / thick3;
double y3 = 12.20 / thick3;
double sy3 = syard3 / y3;
if (thick3 == 1) {
t3 = yard3 / 12.20;
}else if(thick3 == 1.25){
t3 = yard3 / 9.76;
}else if (thick3 == 1.5){
t3 = yard3 / 8.13;
}else if (thick3 == 1.75){
t3 = yard3 / 6.97;
}else if (thick3 == 2){
t3 = yard3 / 6.1;
}
Double result;
if (length3Text.getText().toString().trim().length() == 0) {
result3TotalText.setText(String.format("%.1f", sy3));
grandTotalText.setText(String.format("%.1f", sy3));
result = sy3;
} else {
result3TotalText.setText(String.format("%.1f", t3));
squareYards3Text.setText(String.format("%.1f", yard3));
grandTotalText.setText(String.format("%.1f", t3));
result = t3;
}
return result;
}
}
I just did the check on the first to keep it short.
Any help will be greatly appreciated.
Give us your code so we can help, I need to see your CalculateArea{1,2,3}.
Okay mate, I think I find the solution and it is really easy. When you write OnClick() function like that you need to assign OnClick function on XML file as well so the button knows that it has a "function" to do something.
Here is an example ;
<Button android:id="#+id/mybutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me!"
android:onClick="OnClick" />
Hope it will be helpful.
if (squareYards1Text.getText().toString().trim().length() == 0) {
length1 = Double.valueOf(length1Text.getText().toString());
width1 = Double.valueOf(width1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
}else{
syard1 = Double.valueOf(squareYards1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
// Toast.makeText(MainWindowActivity.this, "inside the 'ELSE' statement", Toast.LENGTH_LONG).show();
}
the code above was the problem, I had to do one more check and change the values if the condition was true like this.
if (squareYards1Text.getText().toString().trim().length() == 0 && length1Text.getText().toString().trim().length() == 0) {
length1 = 0.0;
syard1 = 0.0;
width1 = 0.0;
}else if(squareYards1Text.getText().toString().trim().length() == 0){
length1 = Double.valueOf(length1Text.getText().toString());
width1 = Double.valueOf(width1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
}else{
syard1 = Double.valueOf(squareYards1Text.getText().toString());
thick1 = Double.valueOf(thick1Text.getText().toString());
}
Now it doesn't matter if only one area is being use or 2 or 3 or all of them, it will never find an "invalid double". I had to do this for all areas.
Thanks.

How to convert a text into double in Android

I used the following way to change the string into double but unfortunately this closes the app. The EditText inputtype is "NumberDecimal"
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
//App forceclose here. Not sure why.
final Double a = Double.parseDouble(numA.getText().toString());
final Double b = Double.parseDouble(numB.getText().toString());
calculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
}
});
Try this;
String s = b.getText().toString();
final double a = Double.valueOf(s.trim()).doubleValue();
Perform this check:
if (!numA.getText().toString().equals("")) {
final Double a = Double.parseDouble(numA.getText().toString());
}
if (!numB.getText().toString().equals("")) {
final Double b = Double.parseDouble(numB.getText().toString());
}
An empty string argument to Double.parseDouble() produces a NumberFormatException.
As a suggestion, if you are working on making a calculator(or converter), you should add more checks for invalid input. For example, you should add a check for when the user inputs just the decimal point(.) or input of form (3.).
You may wish to use a try catch because other unparseable data will throw an exception and it may not be the best to rely on the UI to force valid numbers only.
numA = (EditText) findViewById(R.id.numA);
numB = (EditText) findViewById(R.id.numB);
Double a;
Double b;
try {
a = Double.parseDouble(numA.getText().toString());
b = Double.parseDouble(numB.getText().toString());
} catch (NumberFormatException e) {
e.printStackTrace();
a = 0.0;
b = 0.0;
}
final double aFin = a;
final double bFin = b;
calculate.setOnClickListener(new View.OnClickListener() {
//Also, you used your class as an onClickListener you would have to make your doubles final.
#Override
public void onClick(View v) {
numLS.setText("" + ( (- (Double) b) /(2 * (Double) a)));
//Division by zero will produce a NaN you should probably check user input data sanity
}
});

Categories

Resources