Reputation: 2390
I have a cursor reading a SQLite DB and getting a lot of columns, I am storing these columns in a lot of arrays
private ArrayList<String> column1,column2,column3,column4, ... column n;
public getCursorData(Cursor cursor){
if(cursor.moveToFirst()){
do{
column1.add(Cursor.getString("column1"));
column2.add(Cursor.getString("column2"));
column3.add(Cursor.getString("column3"));
column4.add(Cursor.getString("column4"));
...
columnn.add(Cursor.getString("columnN"));
}while(cursor.moveToNext());
}
}
I am looking for a way to store them in a single object (or array, or List, or something), but I can not figure it how to do it
private Object[] object;
public getCursorData(Cursor cursor){
if(cursor.moveToFirst()){
int i=0;
do{
for(int f=0;f<cursor.getColumnCount();f++){
object[i].put(cursor.getColumnName(i), cursor.getString(i)); // I don't know what I am doing!
}
i++;
}while(cursor.moveToNext());
}
}
A different attempt using arrays, where each column is an integer number.
private String[][] data;
public getCursorData(Cursor cursor){
if(cursor.moveToFirst()){
int i=0;
do{
for(int f=0;f<cursor.getColumnCount();f++){
data[i][f]=cursor.getString(f); // this is line 30
}
i++;
}while(cursor.moveToNext());
}
}
This last attempt fails throwing the following error java.lang.NullPointerException: Attempt to read from null array
on line 30 (I marked this line in a comment on the code)
Upvotes: 1
Views: 1532
Reputation: 18677
I think you can create a Custom Object to map those values.. Something like:
public class TableData {
public String mColumn1;
public String mColumn2;
public String mColumn3;
public String mColumn4;
public String mColumn5;
}
public ArrayList<TableData> getCursorData(Cursor cursor) {
ArrayList<TableData> resultList = new ArrayList();
if(cursor.moveToFirst()){
do{
TableData row = new TableData();
row.mColumn1 = Cursor.getString("column1");
row.mColumn2 = Cursor.getString("column2");
row.mColumn3 = Cursor.getString("column3");
...
resultList.add(row);
} while(cursor.moveToNext());
}
return resultList;
}
Edit:
If you want to keep your approach, you should:
private String[][] data;
public void getCursorData(Cursor cursor) {
if (cursor.moveToFirst()) {
data = new String[cursor.getCount()][]; // You have to instantiate your bi-dimensional array
int i = 0;
do {
data[i] = new String[cursor.getColumnCount()];
for (int f = 0; f < cursor.getColumnCount(); f++) {
data[i][f] = cursor.getString(f);
}
i++;
} while (cursor.moveToNext());
}
}
Upvotes: 2