So I am trying to get the result as count from a sql query as follows
ResultSet rs = st.executeQuery("SELECT count(employeeID) FROM employee WHERE " +
"employeeID='"+_empID+"' AND password = '"+_password + "'");
so i am also trying to convert that value to int and I tried the follwing
for (; rs.next();) {
val = (Integer) rs.getObject(1);
}
I have also try
val = Integer.parseInt(rs.getObject(1));
but nothing I get the following errors
java.lang.Long cannot be cast to java.lang.Integer
How can I do this.. so if that returns a 0,3 or 4 that it becomes an integer?
Thank you
EDITED TO: (STILL GETTING ERROR)
long countLong = 0;
for (; rs.next();) {
countLong = rs.getLong(1);
}
if(countLong < 1)
{
isAuthentic = false;
}
else
{
isAuthentic = true;
}
A good trick to use when you are not sure about the exact number type is to cast it to the parent class of all numeric type, Number:
val = ((Number) rs.getObject(1)).intValue();
This will work for all numeric types, eg float, long, int etc.
Use ResultSet.getLong method:
long countLong = resultSet.getLong(1);
//if you really want and you are sure that it fits you can now cast
int count = (int)countLong;
Try a getString() and then Long.parseLong().
Cast it to a string and then to an int or long or whatever you want:
Integer.parseInt(rs.getObject(1).toString());
Related
I store resultset values in the list in following way-
while(rs.next())
{
Comp_Mps_sext ref_drop=new Comp_Mps_sext();
ref_drop.setLogtime(rs.getString(1));
ref_drop.setBeam_current(rs.getString(2));
ref_drop.setBeam_energy(rs.getString(3));
ref_drop.setP44_readback(rs.getString(4));
ref_drop.setP44_setvalue(rs.getString(5));
ref_drop.setP44_vmeset(rs.getString(6));
ref_jsp.add(ref_drop);
}
where Comp_Mps_sext is the Class name.What is the ebst way to trim the values in following format ##.## and then add into the arraylsit.
EDIT-1
ref_jsp is defined as-
List<Comp_Mps_sext> ref_jsp=new ArrayList<Comp_Mps_sext>();
If you just want Strings, then a simple routine to format the result is:
private String hundreths(String in) {
int dotAt = in.indexOf(".");
if (dotAt < 0) // no decimal point??
return in + ".00";
if (dotAt + 2 < in.length())
in += "00";
return in.substring(0, dotAt + 2);
}
Then go thru your results:
ArrayList<String> myArrayList() = new ArrayList<String>();
while(rs.next())
{
Comp_Mps_sext ref_drop=new Comp_Mps_sext();
String result = rs.getString(1)
ref_drop.setLogtime(result);
myArrayList.add(hundreths(result));
....
Note that this will truncate to two places, not round the value.
I want my textfield become like this “99999”
this is my code
while (rs.next()){
int s=rs.getInt("Number");
String num1 = String.valueOf(s);
String n = String.format("%05d",num1);
view.txtcustomernumber.setText(n);
}
why my txtcustomernumber(JTextField) always blank
Try this.
while (rs.next()){
int s=rs.getInt("Number");
String n = String.format("%05d",s);
view.txtcustomernumber.setText(n);
}
It might solve your problem.
I have Parsed some JSON data and its working fine as long as I store it in String variables.
My problem is that I need the ID in an int varibable and not in String.
i have tried to make a cast int id = (int) jsonObj.get("");
But it gives an error message that I cannot convert an object to an int.
So I tried to convert by using:
String id = (String) jsonObj.get("id");
int value = Integer.parseInt(id);
But also that is not working. What is wrong. How is JSON working with int?
My strings are working just fine its only when I try to make them as an int I get problems.
Here is my code :
public void parseJsonData() throws ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(jsonData);
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("LocationList");
JSONArray array = (JSONArray) locationList.get("StopLocation");
Iterator<JSONObject> iterator = array.iterator();
while (iterator.hasNext()) {
JSONObject jsonObj = (JSONObject) iterator.next();
String name =(String) jsonObj.get("name");
String id = (String) jsonObj.get("id");
Planner.getPlanner().setLocationName(name);
Planner.getPlanner().setArrayID(id);
}
}
You may use parseInt :
int id = Integer.parseInt(jsonObj.get("id"));
or better and more directly the getInt method :
int id = jsonObj.getInt("id");
It depends on the property type that you are parsing.
If the json property is a number (e.g. 5) you can cast to Long directly, so you could do:
(long) jsonObj.get("id") // with id = 5, cast `5` to long
After getting the long,you could cast again to int, resulting in:
(int) (long) jsonObj.get("id")
If the json property is a number with quotes (e.g. "5"), is is considered a string, and you need to do something similar to Integer.parseInt() or Long.parseLong();
Integer.parseInt(jsonObj.get("id")) // with id = "5", convert "5" to Long
The only issue is, if you sometimes receive id's a string or as a number (you cant predict your client's format or it does it interchangeably), you might get an exception, especially if you use parseInt/Long on a null json object.
If not using Java Generics, the best way to deal with these runtime exceptions that I use is:
if(jsonObj.get("id") == null) {
// do something here
}
int id;
try{
id = Integer.parseInt(jsonObj.get("id").toString());
} catch(NumberFormatException e) {
// handle here
}
You could also remove that first if and add the exception to the catch.
Hope this helps.
Its very simple.
Example JSON:
{
"value":1
}
int z = jsonObject.getInt("value");
Non of them worked for me.
I did this and it worked:
To encode as a json:
JSONObject obj = new JSONObject();
obj.put("productId", 100);
To decode:
long temp = (Long) obj.get("productId");
I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.
These three test cases illustrate:
int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");
obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
try {
obj = json.get("other");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
// throws exception
}
The question is kind of old, but I get a good result creating a function to convert an object in a Json string from a string variable to an integer
function getInt(arr, prop) {
var int;
for (var i=0 ; i<arr.length ; i++) {
int = parseInt(arr[i][prop])
arr[i][prop] = int;
}
return arr;
}
the function just go thru the array and return all elements of the object of your selection as an integer
For JsonNode use:Integer.parseInt(String.valueOf())
I have a sqlite databse, with alot of tables. Each table has many rows. In one column I have something like this:
[58458, 65856, 75658, 98456, 98578, ... N]
I made a mistake when created the databse (I don't have acces to the initial data anymore ), what I need is to make these numbers with a punct after the second digit and have something like this:
[58.458, 65.856, 75.658, 98.456, 98.578, ... N]
Is there any way I can do this? I prefer Java. Or is it already any tools that can do this?
Use this function to parse the information from each column.
public static String convertColumn(String textF)
{
String textAux = "";
String newText = "[";
int i = 0;
textF = textF.substring(1, textF.length() - 1);
while(i < textF.length())
{
textAux = textF.substring(i, i + 5);
int nrAux = Integer.parseInt(textAux);
i+=7;
int a;
int b;
a = nrAux / 1000;
b = nrAux - a * 1000;
double newNr;
newNr = a + b * 0.001;
newText = newText + newNr + ", ";
}
newText = newText.substring(0, newText.length() - 2);
newText += "]";
return newText;
}
The function will have as parameter a string like [58458, 65856, 75658, 98456, 98578], which you will get from
the SQL table, and the return value will be [58.458, 65.856, 75.658, 98.456, 98.578] which is the value that you need to update the column with.
For SQL the base idea is this:
UPDATE table
SET column = convertColumn(column);
You can use CAST as REAL on the column, and then update as advised in the other answer.
select CAST(YOUR_COL AS REAL) from YOUR_TABLE
Search for CAST in this doc for more info on it: SQLite language guide
This should work if it's a NUMERIC column:
UPDATE <TABLE NAME> SET <COLUMN> = <COLUMN>/1000;
If it is NOT a NUMERIC or REAL column then this should work:
UPDATE <TABLE NAME> SET <COLUMN> = CAST(<COLUMN> AS REAL)/1000;
(Thanks to Goibniu for the pointer)
How can I obtain the value of a boolean field in an SQLite database on Android?
I usually use getString(), getInt(), etc. to get the values of my fields, but there does not seem to be a getBoolean() method.
It is:
boolean value = cursor.getInt(boolean_column_index) > 0;
There is no bool data type in SQLite. Use an int that you fix to 0 or 1 to achieve that effect. See the datatypes reference on SQLite 3.0.
boolean value = (cursor.getInt(boolean_column_index) == 1);
Most of the answers here can result in NumberFormatExceptions or "operator is undefined for the types null, int" if the column you stored the int in was allowed to also hold null.
The decent way to do this would be to use
Boolean.parseBoolean(cursor.getString(booleanColumnIndex));`
though you are now limited to storing the strings "true" and "false" rather than 0 or 1.
An implementation found at Ormlite Cursor also checks for Null which none of the other answers do.
public boolean getBoolean(int columnIndex) {
if (cursor.isNull(columnIndex) || cursor.getShort(columnIndex) == 0) {
return false;
} else {
return true;
}
}
You can also use
boolean value =cursor.getString(boolean_column_index).equals("True");
boolean datatype is not available in Cursor.
you will get the result in an int, so you need to convert that int value to a boolean.
You can either use
boolean b = cursor.getInt(boolean_column_index) > 0;
or
boolean b = (cursor.getInt(boolean_column_index) != 0);
Another option
boolean value = (cursor.getString(column_index)).equals("1");
boolean b = (cursor.getInt(cursor.getColumnIndex("item")) != 0);
Well, that's very simple:
public boolean getBooleanState(SQLiteDatabase db){
boolean result = false;
try{
String QUERY = "SELECT " + BOOLEAN_DATA + " FROM " + TABLE_NAME + " WHERE " + ID + " = 1";
Cursor cursor = db.rawQuery(QUERY, null);
if (cursor.moveToFirst()){
if(cursor.getString(0).equalsIgnoreCase("1")){
result = true;
}
}
c.close();
}catch(Exception ee){
Log.e(TAG, "err getBooleanState: " + TABLE_NAME );
}
return result;
}
For an optional (nullable) Boolean stored as INTEGER, you can create a Kotlin extension:
fun Cursor.getBoolean(columnIndex: Int): Boolean? {
return if (isNull(columnIndex))
null
else
getInt(columnIndex) != 0
}
and use it like this:
val value: Boolean? = cursor.getBoolean(boolean_column_index)
thats what I used:
val work = Work()
work.id = cursor.getInt(0)
work.date = cursor.getString(1)
work.work_value = cursor.getFloat(2)
work.place = cursor.getString(3)
work.wind = cursor.getFloat(4)
work.isCompetition = cursor.getInt(5) > 0
return work
I face the same thing in kotlin.
There was the value "true/false" in the database
and I access it with this code:
cursor.getString(4).toBoolean()
//first as a string then converting them to boolean