I’m writing method wrapping db SELECT statement, that receives SQL query and runs it. Result is collected in Object[][]. Every cell in database may be Integer or String.
I have problem with return array. It’s Object[][], so I loose type.
public Object[][] select(String query) {
Object[][] result = new Object[cursor.getCount()][cursor.getColumnCount()];
Cursor cursor = db.rawQuery(query, null);
//Iterate over cursor (rows)
do {
//Iterate over columns (cells with data of different type)
for(int columnIndex = 0; columnIndex < cursor.getColumnCount(); columnIndex++) {
int type = cursor.getType(columnIndex);
//assume, that there are only two types - String or Integer (actualy there are 3 more types)
if(type == Cursor.FIELD_TYPE_INTEGER) {
result[cursor.getPosition()][columnIndex] = cursor.getInt(columnIndex);
}
else if(type == Cursor.FIELD_TYPE_STRING) {
result[cursor.getPosition()][columnIndex] = cursor.getString(columnIndex);
}
}
} while (cursor.moveToNext());
return result;
}
I do not want to loose type. E.g. want to be able do like this (pseudocode):
//pseudocode:
result = select("SELECT age, name FROM people")
print( "Hello, " + result[0][0] + ". In ten years you'll be " )
print( result[0][0] + 10 )
//Prints: Hello, John. In ten years you'll be 56
Every book about Java says, that I can’t have array of different types. It’s clear.
But how should I hold all this Integers and Strings from DB? I tried to use Collections and Generics, but no luck – new to Java.
Also tried to use some kind of Result value holder:
private class Result {
private Class type;
private Object value;
...
public ??? get() { //??? - int or string - here I have some problems :)
return this.type.cast(this.value);
}
//do NOT want to have these:
public int getInt() { return (int) value; }
public int getString() { return (String) value; }
}
Method select(...) returns Result[][] in this case.
Answered myself:
Understood, that I was trying to code in Java like I did in php. With strong typing I can not make straightforward method, returning all types without explicit casting.
After all I decided to create common data objects and fill them in on selects.
Return a List of Maps with the columns names or indexes as keys like this:
When extracting your data do this:
Collections are surely more powerful than Arrays.
EDIT
Used the
Resultholder class you provided.