unable to parse "" as integer[FC] - android

I have this code to control if a EditTextPreference is null or not:
case R.id.prochain_vidange:
settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String choix_huile = settings.getString("listPref_huile_moteur", "0");
km = settings.getString("km", "");
Log.d("TAG",km);
int x= Integer.valueOf(km);
if (km != "")
{
if (Integer.valueOf(choix_huile) == 0) {
............
The problem is in this line:
int x= Integer.valueOf(km);
What could be the problem ?
Thanks.

If you give Integer.valueOf(String s) a string that is not a valid number, it throws a NumberFormatException. Change the default value to 0:
km = settings.getString("km", "0");
Alternatively, you can catch the exception, and set x to 0:
km = settings.getString("km", "");
int x;
try {
x = Integer.valueOf(km);
} catch(NumberFormatException e) {
x = 0;
}

Integer.valueOf trys to make a new Integer with .parseInteger(String s), "" cant be parsed to a valid number so you get a NumberFormatException
You can catch it with a try catch block or you can simply dont try to make a Integer with the String "".
before:
int x= Integer.valueOf(km);
if (km != "") {
after:
if (km != "") {
int x= Integer.valueOf(km);

Integer.valueOf(km) can throw an exception if the the km string is not able to be parsed as an integer.
However, wrapping it in a try { } catch() block is not an approach I would recommend.
The whole purpose of having a default value on the getString() method in SharedPreferences is that there can be a default value to fall back on if the preference doesn't exist. So the better way to solve this is to modify your settings.getString(...) call to be like this:
km = settings.getString("km", "0");
Then your subsequent call to Integer.valueOf(km) will not have a blank to fail upon.
Is the input string coming from a blank text field where the user can enter any value? If so, it's at that point that you can validate the value that the user entered. By validating the input early on, you won't need to scatter the checking/validating mechanism to other areas of your code.

Related

Convert String from Shared Preferences to Double Value

I've been trying to convert the following string to double value from my Shared Preferences key but still failed even I've tried to follow the solution from the previous Q&A (Android - SharedPreference converting to Double)
Here are my code:
String strCurr_Lat = FM_SharePrefs.getString("FM_Curr_Lat", "");
String strCurr_Lng = FM_SharePrefs.getString("FM_Curr_Lng", "");
String strDest_Lat = FM_SharePrefs.getString("FM_Dest_Lat", "");
String strDest_Lng = FM_SharePrefs.getString("FM_Dest_Lng", "");
Double dCurr_Lat = Double.parseDouble(strCurr_Lat);
Failed and throw an error when reach the assign double variable.
Can anyone assist? Thank you very much.
-sea-
Try this :)
Double dCurr_Lat = Double.valueOf(strCurr_Lat);
To parse in double your string need to in floating number formate. So first you have to check whether it is or not , Otherwise it will throw NumberFormatException .
String strCurr_Lat = FM_SharePrefs.getString("FM_Curr_Lat", "");
if(!TextUtils.isEmpty(strCurr_Lat)){
try {
Double curr_Lat = Double.parseDouble(strCurr_Lat);
}catch (NumberFormatException e){
e.printStackTrace();
Log.e("Parse","String not in floating format");
}
}
if your value is not null then try this it will work.
double dCurr_Lat= Double.parseDouble(strCurr_Lat);

number format exception invalid int

I have to add values to my sq lite from the list view. In my list view there are two edit texts and text view. I just want to get value from each edit text and multiply it to the corresponding text view value. when I am running the app, I need not to enter data to every edit text. due to this I am ending with a "number format exception : invalid int". From other examples I can understand that multiplication on null value may cause the error. how can I skip the null value contained edit texts from the iteration?
this is my code
protected void InsertDb() {
// TODO Auto-generated method stub
DatabaseHelper databasecontroller = new DatabaseHelper(Orders.this);
List<Map<String, String>> data = null;
data = new ArrayList<Map<String, String>>();
if(list != null){
for(int i = 0; i< list.getChildCount();i++){
View vie = list.getChildAt(i);
EditText ed1= (EditText) vie.findViewById(R.id.cases);
EditText ed2 = (EditText) vie.findViewById(R.id.pcs);
String qty = ed1.getText().toString();
TextView tv = (TextView)findViewById(R.id.srp);
String imsrpv= tv.getText().toString();
float srps = Float.valueOf(imsrpv);
int qtys = Integer.valueOf(qty);
float amts = srps * qtys;
String amount = Float.toString(amts);
datanum.put("A",qty );
datanum.put("B",ed2.getText().toString() );
datanum.put("L", amount);
Log.d("value of amnt",amount);
databasecontroller.entercustdetails(datanum);
}
}
Log.v("compleated", data.toString());
}
Thanks in advance..
Check either returning value from edittext is a proper number or it is not null.if a null value is there it may give exeception of numberformat.you have to handle this.
if both are correct then you can also you
float srps=0.0;
int qtys=0;
try
{
srps = Float.valueOf(imsrpv);
qtys = Integer.valueOf(qty);
}
catch (NumberFormatException e)
{
srps =//Default value you want;
qtys =//Default value you want;
}
Hope it works..
Your problem is not how You have parsed the values. For explanation:
parseFloat(), parseInt() will return a primitive type of int and float and valueOf() returns a new type of Integer and Float. Also, parseInt(), parseFloat() will recognize plus and minus signs, valueOf() doesn´t. That´s the difference between these two types/methods. Your problem seems to be, that the value is empty and You can simply get rid of this by:
//set a default float and int
float srps = 0.0;
int qtys = 0;
//now parse the values by checking if the strings are not null or empty
if(imsrpv!=null&&!imsrpv.isEmpty()){
srps = Float.valueOf(imsrpv);
}
if(qty!=null&&!qty.isEmpty()){
qtys = Integer.valueOf(qty);
}
Like I said, if these values have a plus or minus sign and it is important for Your needs, You should use the parse method. Also, You don´t need a new Integer or Float type, so more correct is using parse() method.

How to test string for null value

Have a problem with this code!
I want to check the editText values, if it is null or not...
But it gets stuck at the if segment, doesnt mather if it is a value in the editText or not.
If there is a value in the editText string it should go further and calculate the values.
Second problem I have is the toast, it doesnt show the text in the string variable, it just prints the string link.
private EditText fp;
private EditText fC;
private EditText drive;
private TextView totalcost;
public void CalcButton(View button) {
// Converting strings to float and check if each is NULL (empty)
if (!(fp.getText().equals(null)) || (fC.getText().equals(null)) || (drive.getText().equals(null)))
{
Toast.makeText(getApplicationContext(), "#string/toast", Toast.LENGTH_LONG).show();
}else {
String n1 = fp.getText().toString();
float no1 = Float.parseFloat(n1);
String n2 = fC.getText().toString();
float no2 = Float.parseFloat(n2);
String n3 = drive.getText().toString();
float no3 = Float.parseFloat(n3);
// Calculates the floats
float calc = no1 * no2 * no3;
// Converting and prints out the result
String sum = Float.toString(calc);
totalcost.setText(sum);
}
You should not do it this way, do this instead:
if (!fp.getText().toString().equals("")) {
}
To problem with Toast - use this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
Try to use TextUtils.isEmpty() instead, it checks for null and 0-length String.
On your if statement it should look like:
if (!TextUtils.isEmpty(fp.getText().toString())) {
// Code
}
And on your Toast, change "#string/toast" to R.string.toast or getApplicationContext().getString(R.string.toast);
The code should look like:
// Converting strings to float and check if each is NULL (empty)
if (! (TextUtils.isEmpty(fp.getText().toString()) ||
(TextUtils.isEmpty(fC.getText().toString())) ||
(TextUtils.isEmpty(drive.getText().toString()))))
{
Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.toast), Toast.LENGTH_LONG).show();
}
More on the getString() method here.
EDIT: I've seen that your code also was missing a pair of parenthesis ( ). So your "not" was only applying to the first test.
Something like:
!(test1) || test2 || test3
Instead of
!((test1) || (test2) || (test3))
To check if EditText is empty you do editText.getText().toString().equals("")
So, Your if-statement will look like this:
if (!(fp.getText().toString().equals("")) ||
(fC.getText().toString().equals("")) ||
(drive.getText().toString().equals("")))
And your Toast would be like this:
Toast.makeText(getApplicationContext(), R.string.toast, Toast.LENGTH_LONG).show();
function isNull(int resourceId, boolean getError){
EditText editText= (EditText) findViewById(resourceId);
String strEditText = String.valueOf(editText.getText());
if(TextUtils.isEmpty(strEditText)) {
if(getError) editText.setError("this is null!");
return true;
}else{
return false;
}
}
May be this block gives you a few clues about yours
about If Conditions;
In your 'IF conditions', parentheses seems less than the count it is necessary.
Try to add one more after (!)
I guess it should be like this;
for Negative
if (!(
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
))
for Positive
if (
(String.valueOf(fp.getText()).equals("")) ||
(String.valueOf(fC.getText()).equals("")) ||
(String.valueOf(drive.getText()).equals(""))
)

Android - Check content of a String

I have a string (length 3-8) assigned to a variable (text). I want to check whether the 2nd and 3rd characters are NOT numeric (a letter or symbol or space..or anything other than numbers).
Elementary way to do this could be:
if(((text.charAt(1)-'0')>=0)&&(text.charAt(1)-'0')<10))||((text.charAt(2)-'0')>=0)&&(text.charAt(2)-'0')<10)))
{
//do nothing, since this means 2nd and/or 3rd characters in the string are numeric
}
else
{
// Your condition is met
}
You could also use REGEX's , if your checking is still more complicated.
Here is Another way to achieve this:
boolean isNumeric = true;
String test = "testing";
char second = test.charAt(1);
char third = test.charAt(2);
try {
Integer.parseInt(String.valueOf(second));
Integer.parseInt(String.valueOf(third));
} catch(NumberFormatException e) {
isNumeric = false;
}
System.out.println("Contains Number in 2nd and 3rd or both position: " + isNumeric);
You might make use of the String.IndexOf(String) method, like:
String digits = "0123456789";
String s2 = text.substring(2,3);
String s3 = text.substring(3,4);
boolean valid = (digits.indexOf(s2) > -1) && (digits.indexOf(s3) > -1);

Android: converting String to int

I'm simply trying to convert a string that is generated from a barcode scanner to an int so that I can manipulate it by taking getting the remainder to generate a set number of integers. So far I have tried:
int myNum = 0;
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
}
and
Integer.valueOf(mystr);
and
int value = Integer.parseInt(string);
The first one gives me the error :The method getText() is undefined for the type String
while the last two don't have any compile errors but the app crashes immediately when those are called. I thought it had to do with my barcode scanning intent method but I put it into the OnCreate and still got the error.
Change
try {
myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {
to
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
It's already a string? Remove the getText() call.
int myNum = 0;
try {
myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {
// Handle parse error.
}
You just need to write the line of code to convert your string to int.
int convertedVal = Integer.parseInt(YOUR STR);
Use regular expression:
int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));
output:
i=123;
j=123;
k=123;
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))
output: i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()
output: i=123;
barcode often consist of large number so i think your app crashes because of the size of the string that you are trying to convert to int. you can use BigInteger
BigInteger reallyBig = new BigInteger(myString);
You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected).
Try change.
int NUM=null;
try this
String t1 = name.getText().toString();
Integer t2 = Integer.parseInt(mynum.getText().toString());
boolean ins = myDB.adddata(t1,t2);
public boolean adddata(String name, Integer price)
// Convert String to Integer
// String s = "fred"; // use this if you want to test the exception below
String s = "100";
try
{
// the String to int conversion happens here
int i = Integer.parseInt(s.trim());
// print out the value after the conversion
System.out.println("int i = " + i);
}
catch (NumberFormatException nfe)
{
System.out.println("NumberFormatException: " + nfe.getMessage());
}

Categories

Resources