Force "0" if edittext left blank - java

so I have tried some of the methods in prior posts re this problem yet none of them seem to work for me (user error no doubt).
Basically my calculation button will crash if a edittext is left blank. What I need to happen is that if it is left blank, the edittext is given a value of 0.
Here is my java:
public class kCals extends AppCompatActivity {
EditText firstNumber;
EditText secondNumber;
EditText thirdNumber;
TextView addResult;
Button btnAdd;
double num1,num2,num3,sum;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_k_cals);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
{
firstNumber = (EditText)findViewById(R.id.txtNumber1);
secondNumber = (EditText)findViewById(R.id.txtNumber2);
thirdNumber = (EditText) findViewById(R.id.txtNumber3);
addResult = (TextView)findViewById(R.id.txtResult);
btnAdd = (Button)findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(new View.OnClickListener()
{public void onClick(View v) {
num1 = Double.parseDouble(firstNumber.getText().toString());
num2 = Double.parseDouble(secondNumber.getText().toString());
num3 = Double.parseDouble(thirdNumber.getText().toString());
sum = (num1 * 4) + (num2 * 4) + (num3 * 9);
addResult.setText(String.format("%.2f", sum));}
});
}}}
If anyone can help with this that would be great.
Cheers,
Jess.

It would be best to have a method do this for you like the following.
public double parseDouble(String doubleText) {
if(TextUtils.isEmpty(doubleText)) {
return 0;
}
try {
return Double.parseDouble(doubleText);
} catch(NumberFormatException e) {
// do something if invalid number maybe also return 0?
return 0;
}
}
Then your code becomes
num1 = parseDouble(firstNumber.getText().toString());
num2 = parseDouble(secondNumber.getText().toString());
num3 = parseDouble(thirdNumber.getText().toString());
You could also update the method to pass the EditText objects themselves to avoid all the getText().toString() calls if you wanted to.

How about making a check before u parse.
if(firstNumber.getText().toString() != ""){
num1 = Double.parseDouble(firstNumber.getText().toString());
}
else{
num1 = 0;
}
Note that this will still output exceptions if you allow entries other than numbers in the EditText.

You should try using a function to check for the text. For example :
double getValue(Editable text){
if (text == null || text.length() == 0){
return 0;
} else {
return Double.parseDouble(text.toString());
}
}
and call it :
num1 = getValue(firstNumber.getText());

It is really basic. Parsing a String to a Double may occur some unexpected, so the try-catch is the best choice for you to solve this question.

Check with your edittext value length something like
String s = edittext.gettext().toString();
If(s.length()!=0)
Your stuff

Related

For some reason this is crashing and I have no idea why

I'm doing a termometric scale converter in Android Studio, but when I input a number on any EditText and press the calculate button it crashes and I have no idea why.
This is the MainActivity.java code:
private ViewHolder mViewHolder = new ViewHolder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.mViewHolder.editValueCel = findViewById(R.id.edit_value_cel);
this.mViewHolder.editValueFahr = findViewById(R.id.edit_value_fahr);
this.mViewHolder.editValueKelvin = findViewById(R.id.edit_value_kelvin);
this.mViewHolder.buttonCalculate = findViewById(R.id.button_calculate);
this.mViewHolder.textCelsius = findViewById(R.id.tot_celcius);
this.mViewHolder.textFahr = findViewById(R.id.tot_fahr);
this.mViewHolder.textKelvin = findViewById(R.id.tot_kelvin);
this.mViewHolder.buttonCalculate.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button_calculate){
String valorCel = this.mViewHolder.editValueCel.getText().toString();
String valorFahr = this.mViewHolder.editValueFahr.getText().toString();
String valorKelvin = this.mViewHolder.editValueKelvin.getText().toString();
if (("".equals(valorCel)) && ("".equals(valorFahr)) && ("".equals(valorKelvin))){
Toast.makeText(this, this.getString(R.string.informe_valor), Toast.LENGTH_SHORT).show();
}else {
Double celsius = Double.valueOf(valorCel);
Double fahr = Double.valueOf(valorFahr);
Double kelvin = Double.valueOf(valorKelvin);
if (("".equals(valorFahr)) && ("".equals(valorKelvin))){
this.mViewHolder.textCelsius.setText(String.valueOf(celsius));
this.mViewHolder.textFahr.setText(String.valueOf((9*celsius+160)/5));
this.mViewHolder.textKelvin.setText(String.valueOf(celsius+273));
}else if(("".equals(valorCel)) && ("".equals(valorKelvin))){
this.mViewHolder.textCelsius.setText(String.valueOf(((fahr-32)/9)*5));
this.mViewHolder.textFahr.setText(String.valueOf(fahr));
this.mViewHolder.textKelvin.setText(String.valueOf((5*fahr+2297)/9));
}else if(("".equals(valorCel)) && ("".equals(valorFahr))){
this.mViewHolder.textCelsius.setText(String.valueOf(kelvin-273));
this.mViewHolder.textFahr.setText(String.valueOf((9*kelvin-2297)/5));
this.mViewHolder.textKelvin.setText(String.valueOf(kelvin));
}else{
Toast.makeText(this, this.getString(R.string.erro_muitos_valores), Toast.LENGTH_SHORT).show();
}
}
}
}
private static class ViewHolder{
EditText editValueCel;
EditText editValueFahr;
EditText editValueKelvin;
TextView textCelsius;
TextView textFahr;
TextView textKelvin;
Button buttonCalculate;
}
}
If there's need to post the activity_main.xml code here just tell me and I'll post it.
You convert strings to doubles first
Double celsius = Double.valueOf(valorCel);
Double fahr = Double.valueOf(valorFahr);
Double kelvin = Double.valueOf(valorKelvin);
but judging from the code that follows most likely one or more of the strings are empty which gives a NumberFormatException (or null which gives a NullPointerException) so you need to move the conversions to be inside one of the if/else conditions.
It is better to use isEmpty() than comparing if a string equals ""
if (valorFahr.isEmpty() && valorKelvin.isEmpty()){
Double celsius = Double.valueOf(valorCel);
this.mViewHolder.textCelsius.setText(String.valueOf(celsius));
this.mViewHolder.textFahr.setText(String.valueOf((9*celsius+160)/5));
this.mViewHolder.textKelvin.setText(String.valueOf(celsius+273));
} else if(valorCel.isEmpty() && valorKelvin.isEmpty()){
Double fahr = Double.valueOf(valorFahr);
this.mViewHolder.textCelsius.setText(String.valueOf(((fahr-32)/9)*5));
this.mViewHolder.textFahr.setText(String.valueOf(fahr));
this.mViewHolder.textKelvin.setText(String.valueOf((5*fahr+2297)/9));
} else if(valorCel.isEmpty() && valorFahr.isEmpty()){
Double kelvin = Double.valueOf(valorKelvin);
this.mViewHolder.textCelsius.setText(String.valueOf(kelvin-273));
this.mViewHolder.textFahr.setText(String.valueOf((9*kelvin-2297)/5));
this.mViewHolder.textKelvin.setText(String.valueOf(kelvin));
...
Not knowing how the rest of your app works it might still be a good thing to check that not all 3 strings are empty or that any of them are null as part of this code.
So maybe before the if/else part do
if ((valorFahr == null || valorKelvin == null || valorCel == null) ||
(valorFahr.isEmpty() && valorKelvin.isEmpty() && valorCel.isEmpty())) {
//some error handling
}

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

How to set a maximum integer limit to three so that after pushing a number button for the fourth time, the displayed number wouldn't change?

I'm trying to build a calculator that subtracts one textview from another. One of the textview has a constant value 5. The other textview gets its value after a user presses buttons from 0 to 9. There's also a button for a decimal sign (dot). So, for example, if I press buttons 4, 5, ., 6 and 7, the textview will show 45.67 and a third textview will present the answer (40.67).
This example works fine. But my problem is that I want to limit the number of integers (numbers before the dot) to three. Although I can do this by simply adding setMaximumIntegerDigits to 3, it doesn't work as I'd like. For example, if I press 4, 5 and 3, the textview shows 453. That's fine. However, if I then press another number, for example 7, it shows 537. If I press 8 after that, it shows 378, and so on.
The same problem doesn't exist for decimal numbers. So, my question is, how can I set the actual integer limit so that when I press a number for the fourth time, the application wouldn't change the number in textview?
The code:
public class MainActivity extends AppCompatActivity {
private TextView textResult;
private TextView textSubtractor;
private TextView textSubtractee;
private String display = "0";
private String result = "0";
private SharedPreferences mPrefs;
Button btnDone;
double num1, num2, sub;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textResult = (TextView) findViewById(R.id.textResult);
textSubtractor = (TextView) findViewById(R.id.textSubtractor);
textSubtractee = (TextView) findViewById(R.id.textSubtractee);
btnDone = (Button) findViewById(R.id.btnDone);
textSubtractor.setText(display);
textResult.setText(result);
mPrefs = getSharedPreferences("test", 0);
if (mPrefs != null){
display = mPrefs.getString("display", "0");
sub = mPrefs.getInt(result, 0);
}
updateScreen();
btnDone.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
}
public void onClickNumber(View v) {
if (v.getId() == R.id.btnDot && (display.equals("") || display.contains("."))) {
return;
}
if ((v.getId() == R.id.btn0 ||
v.getId() == R.id.btn1 || v.getId() == R.id.btn2 ||
v.getId() == R.id.btn3 || v.getId() == R.id.btn4 ||
v.getId() == R.id.btn5 || v.getId() == R.id.btn6 ||
v.getId() == R.id.btn7 || v.getId() == R.id.btn8 ||
v.getId() == R.id.btn9) && (display.equals("0"))) {
clear();
updateScreen();
}
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
df.setMaximumIntegerDigits(3);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
public void onClickClear(View v) {
clear();
}
private void clear() {
display = "";
result = "";
textSubtractor.setText("0");
textResult.setText("0");
}
private void updateScreen() {
textSubtractor.setText(display);
}
For a simple solution, I would suggest checking the integer and decimal part of the input when new numeric button is pressed:
//Class constants
final static int INTEGER_SIZE = 3;
final static int DECIMAL_SIZE = 2;
public void buttonPressed(View v) {
if (v.getId() == R.id.btn_dot){ // Handle dot
if(!display.contains("."))
display+=".";
}else{ // Only number values reach this
if(display.equals("0")){ // Handle default zero
clear();
updateScreen();
}
if(display.contains(".")){ //If the number contains a dot, decimal length has to be checked
String[] split = display.split("\\.");
if(split.length==2 && split[1].length()==DECIMAL_SIZE)
return; // New number is not added
}else if(display.length()==INTEGER_SIZE) //Otherwise check the length of the integer (whole sting)
return; // New number is not added
// New number will be added
Button b = (Button) v;
display += b.getText();
updateScreen();
DecimalFormat df = new DecimalFormat("##.##");
df.setRoundingMode(RoundingMode.FLOOR);
num1 = Double.parseDouble(display);
textSubtractor.setText(df.format(num1));
num2 = Double.parseDouble(textSubtractee.getText().toString());
sub = num1 - num2;
textResult.setText(df.format(sub));
}
}
In the long run, you should consider giving user some feedback like disabling the buttons or showing maximum length of the number on UI.

How to get a value from an EditText field and store it in a double variable?

Here is my code first:
public class MainActivity extends AppCompatActivity
{
Spinner dropdown;
EditText e1; //user enters the bill amount before tip here
TextView tipped; //total tipped amount
TextView Bill; //the total amount of the bill including tax
String sdropdown;
double originalBill = 0; //amount that the user enters converted to a double
double result = 0; //result of multiplying bill and tax
String test1; //editText field has to be converted to a string value first
NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(); //currency format object
//Create array of items
String tip [] = {"10%", "15%", "20%", "25%", "30%"};
//Create ArrayAdaptor
ArrayAdapter<String> adaptorTipAmount;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Create the element
dropdown = (Spinner) findViewById(R.id.tipAmount);
tipped = (TextView) findViewById(R.id.tipTotal);
Bill = (TextView) findViewById(R.id.billTotal);
e1 = (EditText) findViewById(R.id.billAmount);
tipped.setText(currencyFormat.format(0));
Bill.setText(currencyFormat.format(0));
//initialize and set adaptor
adaptorTipAmount = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, tip);
adaptorTipAmount.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdown.setAdapter(adaptorTipAmount);
dropdown.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
sdropdown = adapter.getItemAtPosition(position).toString();
//what editText field is initially stored in
test1 = e1.getText().toString();
//test1 string variable gets converted to a double
//originalBill = Double.parseDouble(test1);
//determines the tip amount and does the calculation based on the tip
/* if (sdropdown.equals("10%"))
{
result = originalBill * .10;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("15%"))
{
result = originalBill * .15;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("20%"))
{
result = originalBill * .20;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("25%"))
{
result = originalBill * .25;
tipped.setText(Double.toString(result));
}
else if (sdropdown.equals("30%"))
{
result = originalBill * .30;
tipped.setText(Double.toString(result));
}
*/
tipped.setText("The tipped amount is: " + test1);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
});
}
}
The issue I'm having is whenever I try to get the value from the EditText field and store it in a double the app crashes. I've searched around for solutions to this and have found that if you store the field in a string first and then convert it to a double that would work....well it did not. I'm pretty certain that this is my error although i'm out of ideas on how to solve. I don't want to use a button either. Any help? Thanks
Try this:
How about use toString() at the end of:
tipped.setText(currencyFormat.format(0)).toString();
Hope it Helps.
First off you need to understand the difference between the two types. double is a primitive type whereas Double is an Object. In your global variable: Double originalBill;
//what editText field is initially stored in
test1 = String.valueOf(e1.getText().toString()); //clear any chance if no string in editText
//test1 string variable gets converted to a double
if(test1 != null)
originalBill = Double.parseDouble(test1);
You may need to clean up the String you get from the EditText. Use trim() to remove any whitespace, if any.
//what editText field is initially stored in
test1 = e1.getText().toString().trim();
Have a look at what value is stored in the String
Log.v("parseDouble", "test1 = " + test1);
Ensure it isn't empty, if it is make it "0"
if (test1.isEmpty()) test1 = "0";
//test1 string variable gets converted to a double
originalBill = Double.parseDouble(test1);

how to return number values based on different user input in android

I am trying to create an application that returns a score based on user input.
for example if the user has 1000 posts on a specific site it would return 1. i would end it at 10000.
1000 = 1
2000 = 2 etc.
here is what i have so far and thanks. this site is awesome.
for now i just have each entry adding. value1+value2 etc.
public class DataIn extends Activity {
EditText editPostCount;
EditText editThanksCount;
EditText editRomCount;
EditText editThemeCount;
EditText editKernelCount;
EditText editTutorialCount;
EditText editYearsJoined;
Button mButton;
TextView results;
Button mButton1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.data_in);
android.app.ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
editPostCount = (EditText)findViewById(R.id.editPostCount);
editThanksCount = (EditText)findViewById(R.id.editThanksCount);
editRomCount = (EditText)findViewById(R.id.editRomThreads);
results = (TextView)findViewById(R.id.results);
editThemeCount = (EditText)findViewById(R.id.editThemeCount);
editKernelCount = (EditText)findViewById(R.id.editKernelCount);
editTutorialCount = (EditText)findViewById(R.id.editTutorialCount);
editYearsJoined = (EditText)findViewById(R.id.editYearsJoined);
mButton = (Button)findViewById(R.id.results_button);
mButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//When the button is clicked, call the calucate method.
calculate();
}
});
private void calculate() {
try {
Double value1 = Double.parseDouble(editPostCount.getText().toString());
Double value2 = Double.parseDouble(editThanksCount.getText().toString());
Double value3 = Double.parseDouble(editRomCount.getText().toString());
Double value4 = Double.parseDouble(editKernelCount.getText().toString());
Double value5 = Double.parseDouble(editThemeCount.getText().toString());
Double value6 = Double.parseDouble(editYearsJoined.getText().toString());
Double value7 = Double.parseDouble(editTutorialCount.getText().toString());
//do the calculation
Double calculatedValue = (value1+value2+value3+value4+value5+value6+value7);
//set the value to the textView, to display on screen.
results.setText(calculatedValue.toString());
} catch (NumberFormatException e) {
// EditText EtPotential does not contain a valid double
}
mButton1 = (Button)findViewById(R.id.clear_button);
mButton1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
editPostCount.setText("");
editThanksCount.setText("");
editRomCount.setText("");
editThemeCount.setText("");
editKernelCount.setText("");
editTutorialCount.setText("");
editYearsJoined.setText("");
results.setText("");}
});
} }
You can get the score for every value using a simple division, that is cut to an integer.
In this example I also defined one constant to determine for each different value a specific score factor.
private static final int TOTALCOUNT_SCOREFACTOR = 1000;
int totalCountScore = totalCount / TOTALCOUNT_SCOREFACTOR;
I suggest you not to use doubles, generally int is enough.
I also suggest you to use an array of values, instead of defining all of them separately. In that way, you can easily add or remove values in future.
I hope I am not misunderstanding your question, but if you want the score to add 1 point for every 1000 posts, you simply get the number of posts and divide by 1000. for example:
//value1 is the post count
int calculatedvalue = value1/1000;
So if the number of posts(value1) is 3500, calculatedvalue would be 3.(the remainder is cut off during division)

Categories

Resources