ResultSet How to get String from an object when data is null? - java

In my Oracle table there are columns with different type.
I want to read all columns as number.
String str = resultSet.getString("col1");
The problem is that if column in database is defined as number, and value is
0.5
the returned string will be
.5
I can not use any other getter like getDecimal() and etc.
If I use:
String str = resultSet.getObject("col1").toString();
I'll get an exception if the value is null.

You could use
String str = String.valueOf(resultSet.getObject("col1"));
as a simple workaround to avoid any exceptions. (Not sure why you can't use resultSet.getDouble("col1") though.)

If you don't want to see an empty string rather than the literal "null" for a null value (which is what String.valueOf()) will produce, you can use:
Object value = resultSet.getObject("col1")
String str = value == null ? "" : value.toString();

Related

Reading excel and set String value to Integer using Java POI

I tried to read excel data using java poi and attempt to store in the database.
I read the values from the excel like
Integer.parseInt(formatter.formatCellValue(row.getCell(columnNum)))
in that, the excel may contain null values in the column. So It throws an error
java.lang.NumberFormatException: For input string: ""
when try to set excel values to Integer like
riskVo.setProbability(Integer.parseInt(formatter.formatCellValue(row.getCell(columnNum))));
Note: Probability is an Integer data type.
But It accepts the values if the column is not null.
This is the excel file.
The error occurs in 2nd row 2nd column which contains empty column.If the column has value it works perfectly.
Please note, there is difference between "" and NULL. What you are getting exception is, because of empty string "", which is different than NULL.
For example :
String s = "";
s.length ()// it will return 0
But,
String s = null;
s.length ()// throw NPE.
So, you could probably first check, if String is not null and then check if it not empty.
if(str != null && !str.isEmpty()) {

Read yes/no field from access - Display on java as String

I am having trouble converting an int to string.
I use java to connect to a database (Access).
Now I'm trying to retrieve the value from a YES/NO Field Access but it'sa check box
jlbABC.setText(rs.getString("RightWrong"));
The answer I get is 1 if it is True(YES), and 0 if is False (NO)
How do I change the answer from 1 to YES and 0 to NO?
I don't understand at all what you want, but here is how I normally convert any integer into a string literal.
String values[] = new String[]{"NO", "YES"};
int myValue = ... wherever it comes from;
String myConvertedValue = values[myValue];
You may also check if myValue is in bounds of the array of values.
If you are trying to set the value of a string based on if it is a 0 or a 1 you could use this.
int i = rs.getInt("RightWrong");
String yesno = i == 1 ? "YES" : "NO";
This has the benefit of saying that the result will be "YES" if the value is 1 or "NO" otherwise.

Why my code is giving NumberFormatException?

I have code like this :
int [] arrayOfImages = new int[namesOfSubjectsColorCode.size()];
int y = 0;
for (int x = 0 ; x<namesOfSubjectsColorCode.size();x++) {
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
arrayOfImages[y] = Integer.parseInt(str);
// Integer.parseInt(str);
y++;
}
Here, I have created integer array. Then, I have created string and by using Integer.parseInt() I want to convert it to int so that, my array of integer should generate dynamically. It is giving NumberFormatException.
Please suggest to me a solution for this.
There is no way for this String to be reasonably turned into an int.
String str = "com" + "." + "nyurals" + "." + "R" + "." + "drawable" + "." + nameOfColorCode;
Something like this would be expected:
String str = "1";
Its obvious that it gives you NumberFormatException. Look at your code :
Your str variable contains String which cant parse into Integer value.
Argument for Integer.parseInt() is invalid, you can't pass it string like "com.nyurals.." etc
From the docs:
public static int parseInt(String s)
throws NumberFormatException
Parses the string argument as a signed decimal integer. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' ('\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
And that's exactly what you're getting: NumberFormatException.
EDIT:
You probably want to do something like this:
nameOfColorCode = namesOfSubjectsColorCode.get(x);
String str = "" + nameOfColorCode;
int resourceId = this.getResources().getIdentifier(str, "drawable", this.getPackageName());
arrayOfImages[y] = resourceId;
y++;
If you want to get the int (id) of a resource than you should use
Resources res = activity.getResources();
res.getIdentifier("name","resourceType",activty.getPackageName());
change the name with actual name and resourceType with actual resource type (drawable,color,etc);
As others wrote you don't have an int in your string, it's just an int and not a reference to resoruce
You can access the constants you're trying to reference via http://docs.oracle.com/javase/tutorial/reflect/ but you really don't want to do that.
You'd be better served putting the int's in some form of map of which you can then select some kind of subset dependent on changing information
Integer.parseInt() expects to be given an integer of some sort, not a string of the format com.nyurals.R.drawable.<<nameOfColorCode>>.
Generally, in Android, you would access the variables directly with something like:
R.drawable.SomeName
rather than trying to decode (or, in your case, directly using) the string to get a value.
For example, the following code gets the surface view based on an ID:
SurfaceView sv = (SurfaceView)findViewById(R.id.PfrRightAntiView);
If you do need to dynamically extract a resource based on a string known only at runtime, look into Resources.getIdentifier(), an example of which can be found here.
As per this article, that method may not be the fastest. It may be better to use the reflection method as shown in that link.
May your str returns null so Integer.parseInt(null) return number format exception

Java String(Query String) manipulation

I have a strange scenario. Query string has value first=second=12123423423423432323234
String queryString = request.getParameter("first=second=12123423423423432323234")
So i have to:
capture 'first' and 'second' values
validate the query string has 'first' and 'second'.
Could someone please share how I can achieve this in the best possible way?
I really appreciate your help on this.
I believe your query string should look like
first=firstvalue&second=secondvalue
You can use this in your servlet to print the query string
String firstValue = request.getParameter("first");
String secondValue = request.getParameter("second");
System.out.println("Query String:first="+firstValue+"second=+"secondValue);
In your case, where the query string is
first=second=12123423423423432323234
You could do this
String first = request.getParameter("first");
String second = request.getParameter("second");
if(first.contains("second=")){
second = first.split("second=")[1];
first = first.split("second=")[0];
}
out.println("[First:"+first+"][Second:"+second+"]");
If your parameters are separated properly by & (i.e. first=&second=something), then simply .getParameter("first") and .getParameter("second")
Otherwise, you'd need to play with the string - probably split around =, and for the value of first cut until second is encountered. Though I fail to see how will that work if first has a value: first=foosecond=bar?

java : convert string value to int

from JTable, I try to get values (which are string) of each column from [row 1 to ..end of row] and calcul sum of values as follow :
final ArrayList<String>ValuesList = new ArrayList<String>();
final int nb = myTable.getRowCount();
int sum=0;
for (int i = 1; i < nb; i++)
{
String columnValue = myTable.getColumnValue(i, columnName);
sum=sum+Integer.parseInt(columnValue);
ValuesList .add(columnValue);
}
but I got :
java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
You have at least one empty cell in your table.
Here's a suggestion:
try {
sum += Integer.parseInt(columnValue);
} catch (NumberFormatException nfe) {
// the cell is either empty or not an integer number
// will be treated as zero (0)
}
Note, that the method getColumnValue(int i, String name) is not defined for javax.swing.JTable. If you use a subclass of JTable then the error could be in that class/method too: it may return an empty string instead of a cell value.
I guess you will need to convert an empty String or null value to zero.
So you need to trim the whitespaces when you get the String value and then check if the string is empty.
Here is what your code should look like
final ArrayList<String>ValuesList = new ArrayList<String>();
final int nb = myTable.getRowCount();
int sum=0;
String columnValue = "";
for (int i = 1; i < nb; i++)
{
columnValue = myTable.getColumnValue(i, columnName).trim();
if (!columnValue.isEmpty()) {
sum=sum+Integer.parseInt(columnValue);
}
ValuesList.add(columnValue);
}
Put a check for null/empty string before calling the conversion with parseInst.
if (columnValue != null && !columnValue.isEmpty())
sum=sum+Integer.parseInt(columnValue);
I am not sure about exact syntax so verify before using it.
If columnValue is empty (""), you can't parse it. Just skip the that column in this case, i.e.
if( columnValue != null || columnValue.length() > 0 ) {
//parse and add here
}
Note that I added the check for null just in case, you might not need it if myTable.getColumnValue(...) is guaranteed to never return null.
Also note that you might try and handle other cases as well, depending on what values might be in your table. If blank strings like " " or general alpha-numeric values are allowed, you need to account for that as well.
Finally, why are your values stored as strings if they actually are numbers? Why don't you store them as Integer objects right away?
If the empty String means 0 in your case, you can just check this before:
if (!columnValue.equals(""))
sum=sum+Integer.parseInt(columnValue);
Or even better:
if(!columnValue.isEmpty())
sum=sum+Integer.parseInt(columnValue);
An empty string cannot be converted to an int. If you want to treat it as 0, add the appropriate if statement.
What the compiler is telling you is that you are trying to convert an empty string "" to an int . So you may want to check that you are converting strings that actually represent integers!

Categories