How to read data from list<Object> in Java? - java

I have a list of objects List , being the result of a HQL Query. The Objects of the list contain the data I need. I am doing the following if I know the types of the data :
(Here I know that the query was Select country, globalAmount, average from table)
for (Object record : result) {
Object[] fields = (Object[]) record;
String country = (String) fields[0];
long globalAmount = (Long) fields[1];
double average = (Double) fields[2];
System.out.println("Country "+country );
System.out.println("Global Amount "+globalAmount);
}
The problem is that sometimes, I don't know if I'll be having "Country" or "average" in the Object, and the query can be completely different :
Select average, date, message from table
Then, to retreive data, I have to do the following :
for (Object record : result) {
Object[] fields = (Object[]) record;
double average = (Double) fields[0];
Timestamp date= (Timestamp) fields[1];
String message = (String) fields[2];
System.out.println("date " +date);
System.out.println("Message "+Message);
System.out.println("Average " + Average);
}
Is there any way that I can dynamically retreive data from this List without having Cast problems?
Thank you for your help!

This is just a proto-type. What I did here is got all the column names and then based on the column name I'm type casting it to the required type.
This is just a small trick.
String query = "Select x, y, z from tablename";
//get the columns here
String colums = query.substring(7, query.indexOf("from") - 1).trim();
String []arrColums = colums.split(",");
for(int i = 0; i < arrColums.length; i++)
{
switch(arrColums[i])
{
case "X" : X x = (X)result.get(i);
case "Y" : Y y = (Y)result.get(i);
}
}

It does not to seem possible. I had to use If blocks to figure out which type I am receiving. Quite long but did not have any other option. The solution provided by Uma Kanth is smart but was not suitable for me though.

Related

Set blank row after Unique combination of Column 1 + Column 2 coming from Table in Excel

enter code here
I want to get unique combination of c1 & c2(which are coming from table) like below and create blank row after unique combination. I tried with hashmap but it is taking lot of time. I want to do it in less time.
downloadObjects is a List<Object[]> coming from Database
    
for (Object[] download : downloadObjects) {
for (Object[] download : downloadObjects) {
    String p1 = (String) download[2];
    String c1 = (String) download[0];
    map1.put(p1, c1);
    if (map2.containsKey(platfrom)) {
        List<Object[]> value = map2.get(platfrom);
        value.add(download);
        map2.put(platfrom, value);
    } else {
        List<Object[]> value = new ArrayList<>();
        value.add(download);
        map2.put(platfrom, value);
    }
}
for (Map.Entry<String, String> entry : map1.entrySet()) {
    Row row = null;
    List<Object[]> objects = map2.get(entry.getKey());
    for (Object[] data : objects) {
        row = sheet.createRow(rowIdx++);
        row.createCell(0).setCellValue((String) data[2]);
        row.createCell(1).setCellValue((String) data[1]);
        row.createCell(2).setCellValue((String) data[0]);
        row.createCell(3).setCellValue((String) data[3]);
        row.createCell(4).setCellValue((String) data[4]);
        row.createCell(5).setBlank();
        row.createCell(6).setCellValue((String) data[5]);
    }
    row = sheet.createRow(rowIdx++);
    row.createCell(0).setBlank();
    row.createCell(1).setBlank();
    row.createCell(2).setBlank();
    row.createCell(3).setBlank();
    row.createCell(4).setBlank();
    row.createCell(5).setBlank();
    row.createCell(6).setBlank();
}

trimming the Resultset values stored in object reference upto two decimals

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.

Return list of query in Java 1 dimensional e.g., 1 row is returned

I am having a lot of trouble iterating through all my records. Perhaps, by reading my code someone could help.
private String saveData(Handle handle, String username, String name, String prof, String table) {
String sqlCommand;
Map<String, Object> userResults;
for (Integer tableNum = 1; tableNum < 5; tableNum++) {
//query all tables
sqlCommand = String.format("SELECT varname FROM s" + tableNum.toString());
userResults = handle.createQuery(sqlCommand)
.bind("username", username)
.first();
//attempt to ierate all records
for (Map.Entry<String, Object> entry : userResults.entrySet()) {
Object obj = entry.getValue(); // doesnt have .get(string) as below
}
//get the desired field
logger.debug("Results: " + userResults.toString());
String varname = (String) userResults.get("varname");
if ((varname.toLowerCase()).matches(name.toLowerCase()))
return "";
}
//save data
return name;
}
How do I iterate through each record of the table?
You say this works for row1. You cannot go to the next row as there is .first(); in your handle and you have not tried to fetch next record. Modify your query - the documentation here says you can use .list(maxRows);

SQLlite database, insert punct after second digit

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)

Saving ArrayList in SQLite database in Android

I've been working with SQLite on android and I would like to add an arraylist to a column in a table, and then fetch the data back as an arraylist. The arraylist is a list of Longs. I've noticed that SQL has an option for storing BLOBS, however it looks like I need to convert the arraylist to a byte[] first before being able to store it as a blob in my SQLite database.
If anyone has a solution on how to save arraylists into an SQLite database that would be greatly appreciated. Or is there any other option for saving my array of data, i should consider?
To Insert :
ArrayList<String> inputArray=new ArrayList<String>();
//....Add Values to inputArray
Gson gson = new Gson();
String inputString= gson.toJson(inputArray);
System.out.println("inputString= " + inputString);
use "inputString" to save the value of ArrayList in SQLite Database
To retreive:
Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:
outputarray is a String which is get from SQLiteDatabase for this example.
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
In SQLite use text as format to store the string Value.....
Please forgive me for savagely plagiarizing my previous answer to BLOB vs. VARCHAR for storing arrays in a MySQL table. The other answers over there are also very pertinent.
I think Con's approach is probably better than using java serialization since java's builtin serialization will need additional bytes, and non-java applications will have a harder time dealing with the data.
public static void storeInDB(ArrayList<Long> longs) throws IOException, SQLException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(bout);
for (long l : longs) {
dout.writeLong(l);
}
dout.close();
byte[] asBytes = bout.toByteArray();
PreparedStatement stmt = null; // however you get this...
stmt.setBytes(1, asBytes);
stmt.executeUpdate();
stmt.close();
}
public static ArrayList<Long> readFromDB() throws IOException, SQLException {
ArrayList<Long> longs = new ArrayList<Long>();
ResultSet rs = null; // however you get this...
while (rs.next()) {
byte[] asBytes = rs.getBytes("myLongs");
ByteArrayInputStream bin = new ByteArrayInputStream(asBytes);
DataInputStream din = new DataInputStream(bin);
for (int i = 0; i < asBytes.length/8; i++) {
longs.add(din.readLong());
}
return longs;
}
}
Note: If your lists will sometimes contain more than 31 longs (248 bytes), then you'll need to use BLOB. You cannot use BINARY() or VARBINARY() in MySQL. I realize you're asking about SQLite, but in the spirit of completely plagiarizing my previous answer, I will pretend you're asking about MySQL:
mysql> CREATE TABLE t (a VARBINARY(2400)) ;
ERROR 1074 (42000): Column length too big for column 'a' (max = 255);
use BLOB or TEXT instead
I had two ArrayList<String>, both will 1000+ entries. I looked at blobs and bytes, but for me the solution to speeding up the process and making it usable was by changing the insert method and getting rid of database.insert - Credit for this is here.
private static final String INSERT = "insert into "
+ YOUR_TABLE_NAME+ " (" + COLUMN_1 + ", "
+ COLUMN_2 + ") values (?, ?)";
public void insertArrayData(ArrayList<String> array1,
ArrayList<String> array2) {
try {
database.open();
} catch (SQLException e) {
e.printStackTrace();
}
int aSize = array1.size();
database.beginTransaction();
try {
SQLiteStatement insert = database.compileStatement(INSERT);
for (int i = 0; i < aSize; i++) {
insert.bindString(1, array1.get(i));
insert.bindString(2, array2.get(i));
insert.executeInsert();
}
database.setTransactionSuccessful();
} catch (SQLException e) {
e.printStackTrace();
} finally {
database.endTransaction();
}
try {
database.close();
} catch (Exception e) {
e.printStackTrace();
}
}
It's easily adaptable to Longs and Integers etc and lightening quick. So thankfully I didn't have to scratch my head any longer about blobs and bytes! Hope it helps.
There is an easier way that do such thing in completely another way.
you can make an string that consists of all your array values.
for that make an StringBuilder and append the values continuously and offcource with a separator (like a simbole you which you won't use in your array values . for example virtual '|' .
in code for example :
double[] mylist = new double[]{23, 554, 55};
StringBuilder str = null;
str = new StringBuilder();
for(int i=0;i<mylist.length;i++){
str.append(mylist[i]+"|");
}
String result = str.toString();
db.open();
db.insert(result);
db.close();
when you want to fetch them and use the values. get the column from database pure it to String and with the splite() opration pure each values of array in a column of array than u can easily use it :)
lets do it in code :
String str = db.getdata();
String[] list = str.split("|");
with a simple convert you can use them as double;
double mydouble = Double.parsDouble(list[1].toString());
maybe it is not standard but it is helpfull, hope help ;)
Sounds like you want to serialize the List. Here is a tutorial/intro to the Java Serialization API.
You'll have to do it manually, go through each item in the list and change it to byte before storing it in the database
for (long l : array<long>){
//change to byte here
//Store in database here
}
ArrayList<String> list = new ArrayList<String>();
list.add("Item 1");
list.add("Item 2");
list.add("Item 3");
String joined = TextUtils.join(",", list);
Log.i(TAG, "joined strings: " + joined);
String[] array = TextUtils.split(joined, ",");
Log.i(TAG, "joined strings: " + array[0] + array[1] + array[2]);

Categories