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
Related
i have create a table in sqlite that giving me java.lang.ArrayIndexOutOfBoundsException here is code while returning the array value.
Cursor res = database.rawQuery("select "+QsDatabaseHelper.getItemName()+" from " + QsDatabaseHelper.getItemTableName(), null);
String[] array = new String[res.getCount()];
int i = 0;
while(res.moveToNext()){
String itemName = res.getString(res.getColumnIndex( QsDatabaseHelper.getItemName()));
array[i] = itemName;
Log.d("VALUE ",itemName+"name"); //There i geting all values
i++;
}
return array[i]; //error showing this line
In my fragment i am calling this function to fetching itemname in string []
String[] ItemNameArray = new String[list_counts];
for (int i = 0; i < list_counts; i++) {
ItemNameArray[i] = listcatDb.itemname();
}
you just return array. Because i value is increased inside the while loop. so just return array then use array values in the main thread or if you want to return string use i-1;
return array;
The exception ArrayIndexOutOfBounds is thrown when the index is either negative or greater than or equal to the size of the array.
In while loop the value of 'i' exceeds size of array..
so it should be like
return array[i-1];
instead of,
return array[i];
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.
I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.
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()];