How to get closest double values from ArrayList in Android - java

I've a list of double values named valuelist. I have a edittext and a button . when I press the button it will show the closest double value of edittext from valuelist.how to do that ?btw I'm new to app development and dont know any method to use :(
And my codes are:-
List<Double> list = new ArrayList<Double>();
list.add(1.38);
list.add(2.56);
list.add(4.3);
EditText input = (EditText)findViewById(R.id.etinput);
Button convert = (Button)findViewById(R.id.btconvert);
TextView result = (TextView)findViewById(R.id.tvresult);
double ivalue = String.valueOf(result.getText());
so if ivalue is 2.5 then when I press the button it will set result to 2.56 as it is the nearest double value of array list.
Thanks in advance.

You can iterate over the list and get the difference between the EditText value and the current list item, and the lowest difference value will lead to the nearest item to the EditText value.
List<Double> list = new ArrayList<Double>();
list.add(1.38);
list.add(2.56);
list.add(4.3);
EditText input = (EditText) findViewById(R.id.etinput);
Button convert = (Button) findViewById(R.id.btconvert);
TextView result = (TextView) findViewById(R.id.tvresult);
convert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double ivalue = Double.parseDouble(input.getText().toString());
double difference = Double.MAX_VALUE;
double nearstItem = Double.MAX_VALUE;
for (double item : list) {
if (difference > Math.abs(ivalue - item)) {
difference = Math.abs(ivalue - item);
nearstItem = item;
}
}
result.setText(String.valueOf(nearstItem));
}
});
Make sure to handle the non-double input values to the EditText

Related

Ignore empty calculation errors originating from empty cells

I'm trying to make formulas using text entries for multiple rows only if they have entries though. The problem is it errors out if one of the editText boxes is empty.
Is there a way to ignore the errors and carry on with the rest of the script? Doing calculations if the entries exist?
There are a total of 3 columns with 6 rows for entries. Each of the 3 entries per row should be filled, but if an entry isn't, I don't want it to calculate for that row or have the answer come up as 0.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
e11 = (EditText) findViewById(R.id.editTextTextPersonName3);
e12 = (EditText) findViewById(R.id.editTextTextPersonName4);
e13 = (EditText) findViewById(R.id.editTextTextPersonName5);
t11 = (TextView) findViewById(R.id.textView8);
e14 = (EditText) findViewById(R.id.editTextTextPersonName6);
e15 = (EditText) findViewById(R.id.editTextTextPersonName8);
e16 = (EditText) findViewById(R.id.editTextTextPersonName7);
t12 = (TextView) findViewById(R.id.textView9);
}
public void CalculateMol(View v) {
float entry11 = Float.parseFloat((e11.getText().toString()));
float entry12 = Float.parseFloat((e12.getText().toString()));
float entry13 = Float.parseFloat((e13.getText().toString()));
float result8 = (entry11 * entry12 * entry13/1000000);
t11.setText(String.valueOf(result8+"g"));
float entry14 = Float.parseFloat((e14.getText().toString()));
float entry15 = Float.parseFloat((e15.getText().toString()));
float entry16 = Float.parseFloat((e16.getText().toString()));
float result12 = (entry14 * entry15 * entry16/1000000);
t12.setText(String.valueOf(result12+"g"));
You need to check that your editText values are Empty or not before calculation.
So inside your CalculateMol Method; first validate your input string using this method:
public static boolean isEmptyStr(String Val) {
if (Val == null || Val.isEmpty() || Val.trim().isEmpty() || Val.equalsIgnoreCase("null"))
return true;
else
return false;
}
use above method like this;
public void CalculateMol(View v) {
float entry11;
if(!isEmptyStr(e11.getText().toString())){
entry11 = Float.parseFloat((e11.getText().toString()));
}
}
then apply your calculations.

How to make Toast pop up if EditText field is empty or the inputted value is equal to 0?

First of all, I'm new to Android Studio. I'm currently trying to make a BMI calculator app where the user has to enter their weight and height and select the unit of measurement used for both. A Toast message (R.string.toastError) should pop up upon clicking a button if: (1-2) the EditText fields for weight and height are empty and (3) if the value of HeightInput is less than or equal to zero; else, the calculation should proceed.
The whole math part worked fine when I tested it, but when I left the fields blank, the app just crashes. The Toast pops up though when HeightInput = 0, but not when the EditText field for Weight is left empty at the same time. I think it's the way I wrote the 'if' statement that's giving me a problem.
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
Here's the whole code for reference:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// weight units spinner
final Spinner spinWeightUnit = (Spinner) findViewById(R.id.spinnerWeightUnit);
spinWeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> WeightList = ArrayAdapter.createFromResource(this, R.array.WeightUnits, android.R.layout.simple_spinner_item);
WeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinWeightUnit.setAdapter(WeightList);
// height units spinner
final Spinner spinHeightUnit = (Spinner) findViewById(R.id.spinnerHeightUnit);
spinHeightUnit.setOnItemSelectedListener(this);
ArrayAdapter <CharSequence> HeightList = ArrayAdapter.createFromResource(this, R.array.HeightUnits, android.R.layout.simple_spinner_item);
HeightList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinHeightUnit.setAdapter(HeightList);
// calculate button
Button buttonCalculate = (Button) findViewById(R.id.buttonCalculate);
buttonCalculate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
// weight conversion constant
if (finalWeightUnit.equals("kilograms")) {
constantWeight = 1.00;
} else {
constantWeight = 1 / 2.204623;
}
// height conversion constant
switch (finalHeightUnit) {
case "inches":
constantHeight = 0.0254;
break;
case "centimeters":
constantHeight = 0.01;
break;
case "feet":
constantHeight = 1 / 3.2808;
break;
default:
constantHeight = 1.00;
break;
}
// if edit text is empty
if (editTextWeightInput.getText().toString().length() == 0 || editTextHeightInput.getText().toString().length() == 0 || HeightInput <= 0) {
Toast.makeText(getApplicationContext(), R.string.toastError, Toast.LENGTH_SHORT).show();
} else {
double finalheight = Math.pow((HeightInput * constantHeight), 2.00);
double BodyMassIndex = (WeightInput * constantWeight) / finalheight;
DecimalFormat BodyMassIndexFormat = new DecimalFormat("##.##");
TextView textViewResult = (TextView) findViewById(R.id.textViewBmiResult);
textViewResult.setText(BodyMassIndexFormat.format(BodyMassIndex));
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
I'd appreciate any help! Thanks!
Try below in if statement
if (editTextWeightInput.getText().toString().trim().isEmpty() || editTextHeightInput.getText().toString().trim().isEmpty() || HeightInput <= 0)
When you leave an EditText Empty the getString() function returns a null value. First you need to check for null in the if condition.
if (editTextWeightInput.getText() == null || editTextWeightInput.getText().toString().length() == 0 || HeightInput <= 0)
You need to validate your declaration code also.
// declaration
EditText editTextWeightInput = (EditText) findViewById(R.id.editTextWeightInput);
EditText editTextHeightInput = (EditText) findViewById(R.id.editTextHeightInput);
if(TextUtil.isEmpty(editTextWeightInput.getText().toString())||TextUtil.isEmpty(editTextHeightInput.getText().toString())){
Toast.makeText(getApplicationContext(), R.string.toastError,
Toast.LENGTH_SHORT).show();
}else{
double WeightInput = Double.valueOf(editTextWeightInput.getText().toString());
double HeightInput = Double.valueOf(editTextHeightInput.getText().toString());
String finalWeightUnit = String.valueOf(spinWeightUnit.getSelectedItem());
String finalHeightUnit = String.valueOf(spinHeightUnit.getSelectedItem());
double constantWeight;
double constantHeight;
}

how to operate on data recorded from edit text

I want to take the depth input by the user and mathematically operate on it to obtain cost and then display it to the user. How do I go about doing that?(If didn't notice already, I don't know Java). Thanks.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
cost.setText(x);
}
You need to parse your String obtained from EditText, then perform some operations.
private void estimateCost(View view){
EditText depth = findViewById(R.id.depth);
TextView cost = findViewById(R.id.cost);
String x = depth.getText().toString().trim();
// parse to a number, i.e. int
int depthValue = Integer.parseInt(x);
// calculate total cost
int totalCost = ...
cost.setText(String.valueOf(totalCost));
}
You can create a button to obtain the value. For example:
<Button
android:id="#+id/bt_calc"
android:text="calc"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Then you can catch the click event (put it inside onCreate method):
EditText depth = (EditText) findViewById(R.id.depth);
TextView cost = (TextView) findViewById(R.id.cost);
Button btCalc = (Button) findViewById(R.id.bt_calc);
int costValue;
btCalc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//in here you can
//get the depth from the EditText:
int depthValue = Integer.valueOf(depth.getText().toString());
//do the operations (example):
costValue = depthValue + 1;
//and display the cost in the TextView:
cost.setText(String.valueOf(costValue));
}
});
Good luck!
If your input contains letters as well you won't get int from it with Integer.parseInt()
Use this
int x = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
x = x * 10 + c - '0';
}

Android empty editText is crashing my program [duplicate]

This question already has answers here:
How to parse a double from EditText to TextView? (Android)
(9 answers)
Closed 6 years ago.
First time into Java and I'm trying to create a simple tips calculator for my coworkers at the restaurant I work for, but when I leave one of the editText fields empty the program crashes.
MainACtivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalTipsInput = (EditText) findViewById(R.id.totalTipsInput);
waiter1Hours = (EditText) findViewById(R.id.waiter1Hours);
waiter2Hours = (EditText) findViewById(R.id.waiter2Hours);
waiter3Hours = (EditText) findViewById(R.id.waiter3Hours);
waiter4Hours = (EditText) findViewById(R.id.waiter4Hours);
tipsPerHourView = (TextView) findViewById(R.id.tipsPerHourView);
totalHoursView = (TextView) findViewById(R.id.totalHoursView);
barsCutView = (TextView) findViewById(R.id.barsCutView);
waiter1Pay = (TextView) findViewById(R.id.waiter1Pay);
waiter2Pay = (TextView) findViewById(R.id.waiter2Pay);
waiter3Pay = (TextView) findViewById(R.id.waiter3Pay);
waiter4Pay = (TextView) findViewById(R.id.waiter4Pay);
taxDepositView = (TextView) findViewById(R.id.taxDepositView);
Button calcBtn = (Button) findViewById(R.id.calcBtn);
calcBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
double cWaiter1Hours = Double.parseDouble(waiter1Hours.getText().toString());
double cWaiter2Hours = Double.parseDouble(waiter2Hours.getText().toString());
double cWaiter3Hours = Double.parseDouble(waiter3Hours.getText().toString());
double cWaiter4Hours = Double.parseDouble(waiter4Hours.getText().toString());
double resultTotalHours = cWaiter1Hours + cWaiter2Hours + cWaiter3Hours + cWaiter4Hours;
double resultBarsCut = (totalTips * 7) / 100;
double resultTaxDeposit = resultTotalHours * 3;
double resultTipsPerHour = (totalTips - resultBarsCut - resultTaxDeposit) / resultTotalHours;
double resultWaiter1Pay = cWaiter1Hours * resultTipsPerHour;
double resultWaiter2Pay = cWaiter2Hours * resultTipsPerHour;
double resultWaiter3Pay = cWaiter3Hours * resultTipsPerHour;
double resultWaiter4Pay = cWaiter4Hours * resultTipsPerHour;
totalHoursView.setText(Double.toString(resultTotalHours));
tipsPerHourView.setText(Double.toString(resultTipsPerHour));
barsCutView.setText(Double.toString(resultBarsCut));
waiter1Pay.setText(Double.toString(resultWaiter1Pay));
waiter2Pay.setText(Double.toString(resultWaiter2Pay));
waiter3Pay.setText(Double.toString(resultWaiter3Pay));
waiter4Pay.setText(Double.toString(resultWaiter4Pay));
taxDepositView.setText(Double.toString(resultTaxDeposit));
}
});
}
Tried to do something like this but got an error with .length():
if (double totalTips = Double.parseDouble(totalTipsInput.getText().toString()).length() < 1 || totalTipsInput = null) {
totalTips = 0
} else {
double totalTips = Double.parseDouble(totalTipsInput.getText().toString());
}
Use this method in your class:
public static Double returnDouble(EditText editText)
{
try {
if(editText.getText().toString().isEmpty())
{
return 0d;
}
else
{
return Double.parseDouble(editText.getText().toString());
}
} catch (NumberFormatException e) {
return 0d;
}
}
You can do something like this to make sure that the input to the "parseDouble" is valid:
double totalTips = 0;
Editable totalString = totalTipsInput.getText();
if(totalString.length() > 0){
totalTips = Double.parseDouble(totalString.toString());
}
If the "totalTips" field can take user input you need to make sure they can only enter a valid number. The lazy way might be to put a try/catch around the parseDouble as well, and handle the case where someone may enter something that can't be parsed to a double (ie, empty string, letters, malformed numerical value)
I would recommend not trusting users to always input valid values in the rest of the waiter hours fields as well. You would want to do similar checks on those fields before attempting to parse the input.

Button in Java eclipse

I made a program that computes the geometric mean and my program is already working but i have some sort of errors. Whenever i click the btnCalculate with an empty input in my inputValues my program stops working. how am I going to deal with this error? Thanks:)
final AutoCompleteTextView inputValues = (AutoCompleteTextView) findViewById(R.id.txt_input);
final TextView txtTotalNum = (TextView) findViewById(R.id.txt_totalNumber);
final TextView GeoMean= (TextView) findViewById(R.id.txt_GeoMean);
Button btnCalculate = (Button) findViewById(R.id.btncalculate);
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
});
Button btnclear = (Button)findViewById(R.id.btnclear);
btnclear.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
inputValues.setText("");
txtTotalNum.setText("");
GeoMean.setText("");
}
You are getting errors because your code is trying to split on empty strings or null and then accessing values[] that really have no index at all. Just check if the string fetched by the EditText has a length>0.
#Override
public void onClick(View agr0) {
String fetchedValues = ( inputValues.getText().toString());
if(fetchedValues.length>0)
{
String []values = fetchedValues.split(",");
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
else
{
//alert the user that the field is empty
}
}
#Override
public void onClick(View agr0) {
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
if(values !=NULL){
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
// try this
btnCalculate.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View agr0) {
if(inputValues.getText().toString().length()>0){
String []values = ( inputValues.getText().toString().split(","));//this is the inputed values in the editText using split method
txtTotalNum.setText(Integer.toString(values.length));//calculate the number of inputs
double[] convertedValues = new double[values.length];
double product1 =1.0;
double product=1.0;
for(int a = 0; a < convertedValues.length; a++){
convertedValues[a] =Integer.parseInt(values[a]);
//product *=convertedValues[a];
}
double geoMean = Math.pow(product, product1/convertedValues.length);
GeoMean.setText(Double.toString(geoMean));
}
}
});
Your program stops at
convertedValues[a] =Integer.parseInt(values[a]);
because for an empty input the split array has no values, so its length is 0. And when you try to access values[0]you get an ArrayIndexOutOfBoundsException.
Just check if the input is emty, before splitting it.
if(!inputValues.getText().toString().equals("")){
... // do your stuff
} else {
// show a message
}

Categories