I have a model, lineModel that I am using to populate an array items for my gridAdapter. My model works fine when I populate the entries manually. For example:
lineModel[] items = {
new lineModel(2, "B", "", "#52D017", 5, 10, 30),
new lineModel(3, "C", "", "#000000", 4, 8, 30),
};
However, when populating items with SQLite I receive the ArrayIndexOutOfBoundsException
Specifically:
04-15 15:50:21.322: E/AndroidRuntime(26804): java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
04-15 15:50:21.322: E/AndroidRuntime(26804): at com.idealiner.metrosleepuniversal.model.GridModel.getLines(GridModel.java:68)
Line 68 is when I call lineModel and populate it with the values from cursor.
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
The method getLines() is supposed to return the object array, but somewhere in the while() loop I believe there is a problem, most likely when populating the array.
Any help/advice/guidance would be appreciated.
The entire method, getLines, is below:
public lineModel[] getLines() {
SQLiteDatabase db = getReadableDatabase();
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
String[] sqlSelect = {"*"};
String sqlTables = "lines";
qb.setTables(sqlTables);
Cursor c = qb.query(db, sqlSelect, null, null,
null, null, null);
lineModel[] items = {};
int i=0;
int c_line = c.getColumnIndex("line_id");
int c_name = c.getColumnIndex("line_name");
int c_ccolor = c.getColumnIndex("line_color");
int c_tcolor = c.getColumnIndex("text_color");
c.moveToFirst();
if (c != null) {
while(c.moveToNext()) {
items[i] = new lineModel(i, c.getString(c_line), c.getString(c_name), c.getString(c_ccolor), 0, 0, 0);
i++;
}
c.close();
}
return items;
}
Well, you're creating a zero-length array:
lineModel[] items = {};
so there's no items[i] when you try assigning to it.
If you can use c.getCount(), as Flavio Faria suggests, set the initial length to that. Otherwise, I suggest you use an ArrayList, and .add() items to it as you go along. You can obtain the resulting array with .toArray()
In fact, you might consider using an ArrayList anyway and passing it up as the return value, ,that's very often a good idea.
Another alternative - which depends on how you use those line model items - is to pass an Iterator instead of an array (as what you're doing is essentially iterating into an array.
You can't use "*" together with column names. You must either use only "*" or you must declare each column in the array. So, don't do it like this:
String[] sqlSelect = {"0 _id", "*"};
Add each one of them instead:
String[] sqlSelect = { "line_id", "line_name", "line_color", "text_color"};
Or:
String[] sqlSelect = { "*" };
You must also remove c.moveToFirst() call in order to avoid skipping the first row of the cursor, since c.moveToNext() already does this job for you.
Your array must also be large enough to hold all your items:
lineModel[] items = new lineModel[c.getCount()];
Besides that, keep in mind that class names in Java start with a capital letter.
Related
I am creating function for Sqlite database and getting "variable might not initialized" error. I am trying to store sqlite data in string array.
public String[] gettitle()
{
String title[];
String s = "select Title from User_DB;";
SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(s,null);
int a = 0;
while(cursor.moveToNext())
{
title[a] = cursor.getString(0);
a++;
}
return title;
}
it says title[] is not initialized but I dont understand why. I clearly initialized it.
You declare title. Allowed C language style is String title[]. In java one keeps the type expression together: String[] title;
String[] title;
This variable is uninitialized, reserves a memory slot for an array object, but the memory is not filled, initialized; it contains garbage. At its first usage of title the compiler issues an error.
In contrast class fields are initialized automatically by a default: here null, but for other types 0, false, 0.0 and so on.
Initialize the variable: give it an initial value.
For arrays that means set an array object. Arrays are fixed length, cannot grow, and thus:
String[] title;
title = new String[10];
Or shorter:
String[] title = new String[10];
Like fields also array elements are initialized with defaults, null.
Note you initialized a: int a = 0;.
Now you can use the array object through the variable:
title[a] = cursor.getString(0);
This was the point where the compiler saw the usage of a variable that still did not have a value.
So the code becomes:
public String[] loadTitles() {
String[] titles = new String[100];
String sql = "select Title from User_DB";
SQLiteDatabase db = getReadableDatabase();
int a = 0;
try (Cursor cursor = db.rawQuery(sql, null)) {
while (a < titles.length && cursor.moveToNext()) {
titles[a] = cursor.getString(0);
a++;
}
} // Calls cursor.close();
return Arrays.copyOf(titles, a);
}
Array.copyOf(array, newLength) make copy of the original array with as new length the number of read titles.
I have added the (weird) try-with-resources syntax which ensures that cursor is closed, even on exception or return happening inside the block.
I try to convert my Cursor data to a arraylist. But at the end all the data in the arraylist is overwrited with the last row. What do i do wrong?
Cursor c = myDbHelper.getLvl1Cata();
String[] data = new String[3];
c.moveToFirst();
while(!c.isAfterLast()) {
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
c.moveToNext();
}
Try this
Cursor c = myDbHelper.getLvl1Cata();
String[] data;
if (c != null) {
while(c.moveToNext()) {
data = new String[3]; // Note this addition
data[0] = Integer.toString(c.getInt(0));
data[1] = c.getString(1);
data[2] = Integer.toString(c.getInt(2));
Log.e("cc", data[1]);
catalogueData.add(data);
}
c.close();
}
data is an array of strings. In the original code, you added the same array to your catalogueData structure several times. You changed the value of the array's contents each time, but it was still the same array object. So you ended up with catalogueData holding several references to a single array, and that array can only have one value for data[0]: the last thing you set it to.
This answer fixes that by using a new and different array for each row in the cursor.
Try this:
if(mycursor!=null){
do{
TextView name = (TextView)view.findViewById(R.id.contact_name);
name.setText(cursor.getString(cursor.getColumnIndex
(Displayname)));
mycursor.moveToNext();
}while (mycursor.isLast());
}
Put String[] data = new String[3]; into the while loop. You're overwriting the array object with each iteration.
Pretty sure this is an easy one, but i'm getting confused by all the examples that adapt the data returned from a cursor into different views. I just want to run a rawquery and put each item of data returned into a float array (so that i can add them up later). What do i need to use for this? Thanks
You'll still have a cursor when you query your database, but once you got the cursor you could iterate over it, pulling out the values you need into an array, like this:
DbAdapter db = new DbAdapter(mContext);
int columnIndex = 3; // Whichever column your float is in.
db.open();
Cursor cursor = db.getAllMyFloats();
float[] myFloats = new float[cursor.getCount()-1];
if (cursor.moveToFirst())
{
for (int i = 0; i < cursor.getCount(); i++)
{
myFloats[i] = cursor.getFloat(columnIndex);
cursor.moveToNext();
}
}
cursor.close();
db.close();
// Do what you want with myFloats[].
Don't minus by 1 in float[] myFloats = new float[cursor.getCount()-1]; because (int i =0) or i start from 0. If you use it, will appear Java.lang.IndexOutOfBoundsException. You need array index until [cursor.getCount()], not until [cursor.getCount()-1]. So the correct thing is float[] myFloats = new float[cursor.getCount()];
I have a db collection (SQLite) and i want to create an array of the ROW_IDS. I think the following should work:
db.open();
String Chapter = "Something";
Cursor c = db.getSetsByChapter(Chapter);
int[] ids = {};
if (c.moveToFirst()){
int i = 0;
do {
ids[i] = Integer.parseInt(c.getString(0));
i++;
} while (c.moveToNext());
}
db.close();
Toast.makeText(this,"The array contains " + ids.length + " elements",Toast.LENGTH_LONG).show();
but i keep getting:
Unable to start activity Component ... java.lang.ArrayIndexOutOfBoundsException
I'm very new to java and android coding. I have been at this for 3 days and loosing it!
First, you need to show us what line the exception is occuring.
Second, int[] ids = {}; declares an array of ints with length 0. You then try to
ids[i] = Integer.parseInt(c.getString(0));
put data into index 0. This isn't possible, and thus an array index out of bounds exception.
You need to allocate the array. Use a List<int> and then convert the list to an integer array
I get a String data from Cursor, but I don't know how to convert it to Array. How can I do that?
String[] mString;
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
}
mString = mTitleRaw ????
You could just wrap mTitleRaw into a single element array like so:
mString = new String[] { mTitleRaw };
Update:
What you probably want is to add all the rows to a single array, which you can do with an ArrayList, and mutate back to a String[] array like so:
ArrayList strings = new ArrayList();
for(cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String mTitleRaw = cursor.getString(cursor.getColumnIndex(SBooksDbAdapter.KEY_TITLE_RAW));
strings.add(mTitleRaw);
}
Sting[] mString = (String[]) strings.toArray(new String[strings.size()]);
As Pentium10 pointed out marshall_law's code has a bug in it. It skips the first element in the cursor. Here is a better solution:
ArrayList al = new ArrayList();
cursor.moveToFirst();
while(!cursor.isAfterLast()) {
Log.d("", "" + cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_PROFILE_NAME)));
String mTitleRaw = cursor.getString(cursor.getColumnIndex(ProfileDbAdapter.KEY_ID));
al.add(mTitleRaw);
cursor.moveToNext();
}
As I said, this code will include the first element in the cursor.