Float variable != null not working - java

If (loanAmtValue!=null) is used..it throws an error ie."Operator != cannot be applied to float,null". Plzz sum1 come up with a solution to this prob.. The app crashes if no value is given in that field. So I was trying to use null condition check so that app doesn't crash even if no value is given.
public class SICalculatorActivity extends Activity implements View.OnClickListener {
private Button submit;
private Button submit2;
SeekBar sb;
TextView yrs;
EditText loanAmt;
EditText roi;
TextView siResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
final int years;
sb = (SeekBar)findViewById(R.id.set_years);
yrs = (TextView)findViewById(R.id.years);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
yrs.setText(sb.getProgress()+" year(s)");
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
addButtonClickListener();
}
private void addButtonClickListener() {
submit = (Button)findViewById(R.id.button);
submit.setOnClickListener(this);
submit2 = (Button)findViewById(R.id.button2);
submit2.setOnClickListener(this);
}
#Override
public void onClick(View view) {
float loanAmtValue = 0;
float roiValue = 0;
double answer=0;
float y = sb.getProgress();
loanAmt = (EditText)findViewById(R.id.amt);
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
roi = (EditText)findViewById(R.id.roi);
roiValue = Float.parseFloat(roi.getText().toString());
if (loanAmtValue != null && roiValue != null){
case R.id.button:
answer = (loanAmtValue * roiValue * y) / 100;
siResult = (TextView) findViewById(R.id.result);
siResult.setText("Simple Interest for Amount Rs." + loanAmtValue + " and ROI " + roiValue + "% for "+y+" year(s) is = " + String.format("%.2f", answer));
loanAmt.setText("0");
roi.setText("0");
break;
}
}
else
{
siResult.setText("Please provide valid details");
}
}
}

float is a primitive data type and not an object. null check is used for objects.
For primitives you should use the default values check. For float the default value is 0.0f.
Read following:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
http://www.c4learn.com/java/java-default-values/

It looks like your problem is here :
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
This line will throw NumberFormatException if loanAmt doesn't contain a String that can be converted to a float.
You can check that the String is not empty before attempting to convert to float :
if (loanAmt.getText() != null && !loanAmt.getText().isEmpty()) {
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
}
This would still throw an exception if the user enters an invalid String, so you'll have to catch the exception :
if (loanAmt.getText() != null && !loanAmt.getText().isEmpty()) {
try {
loanAmtValue = Float.parseFloat(loanAmt.getText().toString());
catch (NumberFormatException ex) {
loanAmtValue = 0.0; // or some other default value
}
}

Null is used for objects. If an object is null, then this means this variable points to nowhere.
Obj a = null // a points nowhere
a = new Obj() // now a points to a place in the memory (a references an Obj object in the memory
And float is not an object type, it's a primitive type. But be carefull if you make comparison like: x == 0.0 (float comparison is not like comparison integers!).

To complete the answers, You cannot check if a float is null, like everybody said here. What You can do is, like "Der Golem" said check it if it is !=0, if You want to get sure that the value is not 0 (not the same like null!!!). BUT:
To prevent a NumberFormatException You also have to be sure, that Your catched value from the edit text field is a number. You can do it with TextUtils:
android.text.TextUtils.isDigitsOnly(CharSequence str).
In Your case, You should do it like this:
loanAmt = (EditText)findViewById(R.id.amt);
String loanAmtString = loanAmt.getText().toString();
if(android.text.TextUtils.isDigitsOnly(loanAmtString)){
loanAmtValue = Float.parseFloat(loanAmtString);
}
roi = (EditText)findViewById(R.id.roi);
String roiString = roi.getText().toString();
if(android.text.TextUtils.isDigitsOnly(roiString)){
roiValue = Float.parseFloat(roiString);
}

In my opinion, there are two ways to enforce user to enter only float values.
Using inputType for EditText
Checking entered text by a regular expression
Pattern ptrn = Pattern.compile("^\\d*\\.\\d*$");
String enteredText = ...;
if(ptrn.matcher(enteredText).matches()){
// try to parse the string here
}

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 can calculate the value of variable at the first time on onClickListener event?

I have an operation in which the value of a variable changes during the following process. The following code shows this operation.
private long checkOffCode(String pChode) {
final long[] percent = {0};
APIGettingPosts apiGettingPosts = new APIGettingPosts(MainActivity.this, "get_off_code.php");
apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
#Override
public void onReceived(List<Posts> posts) {
if (posts == null || posts.isEmpty()) {
// There is no value on sever...
} else {
for (int i = 0; i < posts.size(); ++i) {
// If the code in serve is equal with pCode],
// change the price value....
if (pChode.equals(posts.get(i).getCode())) {
percent[0] = Long.valueOf(posts.get(i).getPercent());
}
}
}
}
});
return percent[0];
}
The checkOffCode function receives a code, and returns a variable named percent if its value is equal to the value stored in the server.
In the event setOnClickListener of the btnPurchase button, this value is called, and using of its value, the price variable is computed.
The code for this section is as follows:
btnPurchase.setOnClickListener(new View.OnClickListener(){
long percent = 0;
#Override
public void onClick (View view){
percent = checkOffCode("MYCODE");
if (percent != 0) {
// update price value...
price = price - price * percent / 100;
Log.e("Success >>", String.valueOf(price));
} else {
Log.e("Failure >>", String.valueOf(price));
}
}
});
The problem is that when I click on the btnPurchase button for the first time, the previous value of percent [percent = 0] is calculated in the operation, but when I click on the button for the second time, the variable price is calculated with the new percent value.
The output Log cat is shown in both first and second clicks respectively as follow:
08-28 00:45:04.589 28467-28467/? E/Success >>: 125000
08-28 00:45:11.425 28467-28467/? E/Success >>: 16000
The question is: How can I calculate the value of price with the new percent value at the first time?
There is no relation with whether you click the button first or second time.
The problem is that you try to get the return value from checkOffCode directly without being sure about that onReceived has been called. You can change the code like this:
private void checkOffCode(String pChode) {
final long[] percent = {0};
APIGettingPosts apiGettingPosts = new APIGettingPosts(MainActivity.this, "get_off_code.php");
apiGettingPosts.getOffCode(new APIGettingPosts.OnOffCodeReceived() {
#Override
public void onReceived(List<Posts> posts) {
if (posts == null || posts.isEmpty()) {
// There is no value on sever...
} else {
for (int i = 0; i < posts.size(); ++i) {
// If the code in serve is equal with pCode],
// change the price value....
if (pChode.equals(posts.get(i).getCode())) {
percent[0] = Long.valueOf(posts.get(i).getPercent());
}
}
}
if (percent[0] != 0) {
// update price value...
price = price - price * percent[0] / 100;
Log.e("Success >>", String.valueOf(price));
} else {
Log.e("Failure >>", String.valueOf(price));
}
}
});
}
btnPurchase.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkOffCode("MYCODE");
}
});
You can try adding boolean that if firstClicked, calculate the price, so if you tap again for the second time, the calculation will not triggered. This is the example:
First make boolean variable outside the onClick function:
private Boolean isFirstClicked = false;
Then modify your onClick function:
if (!isFirstClicked) {
// update price value...
isFirstClicked = true
price = price - price * percent / 100;
Log.e("Success >>", String.valueOf(price));
} else {
Log.e("Failure >>", String.valueOf(price));
}

java.lang.NumberFormatException: Invalid int: “” [duplicate]

This question already has answers here:
Edit Text shows exception Invalid Int ""
(5 answers)
Closed 6 years ago.
I am getting java.lang.NumberFormatException: Invalid int: error
I believe the declarations are appropriate
I have taken input of numbers in string earlier itself.
The below part only calculates the sum.
Second part is a continuation of 1st part.
Declaration is given below:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText num1 = (EditText)findViewById(R.id.num1);
final EditText num2 = (EditText)findViewById(R.id.num2);
final EditText resu = (EditText)findViewById(R.id.resu);
resu.setFocusableInTouchMode(false);
resu.setFocusable(false);
resu.setClickable(false);
final Button plus = (Button)findViewById(R.id.plus);
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
On click program:
plus.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View view) {
try{
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}catch(Exception e){
resu.setText(""+e);
}
}
);
Move the following code inside your onlick() method, because in your oncreate() if the EditText is empty it will return empty String (""), so you need to get the value when the button is clicked, not before it:
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
To:
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try {
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
} catch(Exception e) {
resu.setText(""+e);
}
}
});
Problem lies on Integer Object to float primitive type conversion. I think if you give an input a Whole Number then your code should work fine. code
float sum = Integer.valueOf(n1) + Integer.valueOf(n2);
But if it's not a whole Number then inorder to incounter NumberFormatException you're failing to convert String into your appropriate primitive Data type.
And also check for empty String ("") in n1 and n2 by if(n1=="")
plus.setOnClickListener(new Button.OnClickListener() {
public void onClick(View view) {
try
{
final String n1 = num1.getText().toString();
final String n2 = num2.getText().toString();
if(n1==""){
n1="0";
}
float sum = Float.valueOf(n1) + Float.valueOf(n2);
String a = Float.toString(sum);
a = a.trim();
resu.setText(""+a);
}
catch(Exception e)
{
resu.setText(""+e);
}
}
});

How to pass data from a class and used in another class for calculation

i'm trying to do this feature where i calculate the calories needed in BMIcalculation class, then i created another class called CalorieIntake where in here i'll calculate the total calorie intake. (i do this by extends the BMIcalculation class.)
Then when i click on the 'Check' button, it should compare between this two value and show the interpretation. However i keep getting error at the 'interpretDiff(float diffValue)' part it mentioned it must return with a String value.
Here are my codes..pls help me to check where to problem is. Or is there a better way to do so? pls advice me. Thanks a lot..
public class CalorieIntake extends BMIcalculation {
TextView counter1;
Button compare;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.form_calorieintake2);
Button btn_calcIntake = (Button) findViewById(R.id.button_calcIntake);
btn_calcIntake.setOnClickListener(btnListener_calcIntake);
counter1 = (TextView) findViewById(R.id.textView_totalCalorieIntake);
Button compare = (Button) this.findViewById(R.id.checkIntake);
compare.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
try {
if ((!counter1.equals("")) && (!caloriesresult.equals("")))
{
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
}
}catch (Exception k)
{ System.out.println(k);
Toast.makeText(CalorieIntake.this, "Error", Toast.LENGTH_SHORT).show();
}
}
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
{
return "Eat more";
}
}
private float calDiff(float calorieIntake, float calorieNeed) {
return (float) (calorieIntake - calorieNeed);
}
});
}
In interpretDiff, what happens if diffValue is not less than 100? You return nothing. However, java requires that you return something, as that is what the declaration of the method implies.
A solution would be:
private String interpretDiff(float diffValue)
{
if (diffValue < 100)
return "Eat more";
return "Eat less";
}
The else statement for if diffValue is not less than 100 is not necessary here because the second return statement is only called if diffValue >= 100 (since hitting a return statement exits out of the method).
With regards to the issue of the exception being thrown, and the Toast error being called, that can only happen as a result of the following code:
TextView compareText = (TextView)findViewById(R.id.compareLabel);
EditText counter1E = (EditText) findViewById(R.id.textView_totalCalorieIntake);
EditText caloriesresultE = (EditText)findViewById(R.id.caloriesText);
float calorieIntake = Float.parseFloat(counter1E.getText().toString().trim());
float calorieNeed = Float.parseFloat(caloriesresultE.getText().toString().trim());
float diffValue = calDiff(calorieIntake, calorieNeed);
String calInterpretation = interpretDiff(diffValue);
compareText.setText("Difference of" + diffValue + " : " + calInterpretation);
Assuming findViewById doesn't have an issue in it, the error is probably coming from getting the text of counter1E, caloriesresultE (if they are null). If neither of those are null, then check to make sure callDiff and interpretDiff don't have bugs in them. Finally, make sure compareText is not null.

Plus or minus minor glitch in my android calculator

I have made an android calculator, and I have added the +/- button to it recently. The problems I am facing is, firstly when I use it, and press the equal button, the app crashes. Moreover as soon as I click +/- button, the digits turn into a float value, and when I type any number the number value continues after the decimal. Example: I have 200 and I press +/- the number becomes 200.0 and when I type any number it becomes 200.01. How do I overcome this problem? Can someone please let me know what are the changes required in my code? Here it is.
Thank you. :)
public class MainActivity extends Activity {
Typeface font1, font2;
TextView tv1;
private EditText Scr; //textbox screen
private float NumberBf; //Save screen before pressing button operation;
private String Operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
font1=Typeface.createFromAsset(getAssets(), "digits.ttf");
Scr=(EditText)findViewById(R.id.editText);
Scr.setTypeface(font1);
font2=Typeface.createFromAsset(getAssets(), "alexbrush.TTF");
tv1=(TextView)findViewById(R.id.textView1);
tv1.setTypeface(font2);
Scr = (EditText) findViewById(R.id.editText);
Scr.setEnabled(false);
btnClick = new ButtonClickListener();
int idList[] = {R.id.button0,R.id.button7, R.id.button1, R.id.button8,R.id.button9,R.id.button4,
R.id.button5,R.id.button6,R.id.button,R.id.button2,R.id.button3,R.id.buttonDot,
R.id.buttonMul,R.id.buttonDiv,R.id.buttonAdd,R.id.buttonSub,R.id.buttonC,
R.id.buttonEq, R.id.buttonSqrt, R.id.buttonsquare, R.id.buttonNp
};
for(int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void mMath(String str){
NumberBf = Float.parseFloat(Scr.getText().toString()); //save the screen
Operation = str; //save operation
Scr.setText("0"); //Clear screen
}
public void getKeyboard(String str){
String ScrCurrent = Scr.getText().toString();
if(ScrCurrent.equals("0"))
ScrCurrent = "";
ScrCurrent += str;
Scr.setText(ScrCurrent);
}
public void mResult(){
float NumAf = Float.parseFloat(Scr.getText().toString());
float result = 0;
if(Operation.equals("+")){
result = NumAf + NumberBf;
}
if(Operation.equals("-")){
result = NumberBf - NumAf;
}
if(Operation.equals("*")){
result = NumAf * NumberBf;
}
if(Operation.equals("/")){
result = NumberBf / NumAf;
}
Scr.setText(String.format("%10d", result));
}
public void fnSqrt(){
double Number = Double.parseDouble(Scr.getText().toString());
Number = Math.sqrt(Number);
Scr.setText(String.valueOf(Number));
}
public void fnSquare(){
float Number1 = Float.parseFloat(Scr.getText().toString());
Number1 = pow(Number1, 2);
Scr.setText(String.valueOf(Number1));
}
public void fnNp(){
float Number = Float.parseFloat(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
}
private float pow(float number1, int i) {
return number1*number1;
}
private class ButtonClickListener implements OnClickListener{
public void onClick(View v){
switch (v.getId()){
case R.id.buttonC: //Clear screen
Scr.setText("0");
NumberBf = 0;
Operation = "";
break;
case R.id.buttonAdd: //function Add
mMath("+");
break;
case R.id.buttonSub:
mMath("-");
break;
case R.id.buttonMul:
mMath("*");
break;
case R.id.buttonDiv:
mMath("/");
break;
case R.id.buttonEq:
mResult();
break;
case R.id.buttonSqrt:
fnSqrt();
break;
case R.id.buttonNp:
fnNp();
break;
case R.id.buttonsquare:
fnSquare();
break;
default:
String numb = ((Button) v).getText().toString();
getKeyboard(numb);
break;
}
}
}
}
Concerning your first problem: Do you get a nullpointer exception?
public void mResult(){
float NumAf = Float.parseFloat(Scr.getText().toString());
does not prevents your statement to try to turn a null String into a float which obviously will let your app crash. So include a mechanism to catch the null value before.
case R.id.buttonEq:
if (Scr.getText() != null)
mResult();
break;
I think this is the easiest way to prevent your mResult() from getting a null value.
For your second problem: It becomes a float because you do
float Number = Float.parseFloat(Scr.getText().toString());`
When you cast your 200 into a float it becomes 200.00 which will be returned as a string.
EDIT: I realized that you also have a dotButton (your code is really messy). The suggested alternative of course does not work with decimal numbers because it always casts your numbervalue. To prevent this behaviour maybe you can implement a simple if/else statement.
public void fnNp() {
if (Scr.getText().toString().contains(".")) {
float Number = Float.parseFloat(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
} else {
int number = Integer.parseInt(Scr.getText().toString());
Number = Number*(-1);
Scr.setText(String.valueOf(Number));
}
}
You need to do a if statement in mResult that checks whether the float has a absolute difference to a float of the int of the float , less than , say Float.MIN_VALUE , and then get the toString of the int of the float instead if it is.
Wrap the call Scr.setText( Float f) , in a function setScreenTextWithNumber(Number n)
and do the checking there.
If you just check for the decimal point, then 2.0000 / 2 = 1.000 if that is what you want.
Otherwise checking for significant differences makes a call that a number that is not significantly different from the nearest integer is an integer.

Categories