Sqlite : ArrayIndexOutOfBoundsException when try to fetch array from database - android

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];

Related

load text from String array and set text to textview is very slow in big string array

hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.

how to loop through 2d array and make the result appear in table form in android

HI below is the code which gets the four columns data from the curson and put in the 2d array. basically there are two issues one is that i get the last value as nullnullnullnull means all for columns are fetched as null.
the seconds is that i want to print the array in multitextline or if any other widget availabe so that i get four fields in a row. like
id rule_body rule_con boole
0 abc def 1
0 a f 0
c.moveToFirst();
int i=0;
while(c.moveToNext()) {
String id = c.getString(c.getColumnIndex("id"));
String rb = c.getString(c.getColumnIndex("rule_body"));
String cn = c.getString(c.getColumnIndex("rule_cons"));
String bl = c.getString(c.getColumnIndex("boole"));
table[i][0] = id;
table[i][1] = rb;
table[i][2] = cn;
table[i][3] = bl;
++i;
}
for(int a=0;a<count_row;a++)
for(int b=0;b<count_col;b++) {
obj_ml.append(String.valueOf(table[a][b]));
}
so far i am getting all the result in a single line. any help will be appreciated.
Change your for-loop as below
for (int a=0;a<count_row;a++)
{
for(int b=0;b<count_col;b++)
{
obj_ml.append(String.valueOf(table[a][b]));
}
// add to obj_ml new line character '\n'
obj_ml.append("\n");
}

Array index out of bounds exception android

I am trying to get the data from database table via php file and displaying it in android. In php file I seperated each column with "#".
So now I am getting values like 4#2012-11-06#test1#test2. But for some columns there is not data. So the values are comng like 5###.
Here when I splitting with # and displaying the data it is throwing out of bounds exception. How can I resolve this issue?
Code:
String st="1#2012-10-30#test1#2#2012-10-30#test2#3#2012-11-06#test3#9##test1#21###22###23###";
String[] val = st.trim().split("#");
for (int i = 0; i < val.length; i++)
{
String str = val[i];
String arr[] = str.split("#");
System.out.println("arr0" + arr[0]);
System.out.println("arr1" + arr[1]);
System.out.println("arr2" + arr[2]);
}
try as using Pattern.compile to split your current string :
String your_string = "4#2012-11-06#test1#test2";
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for Handling if array index contain empty string change your code as:
for (int i = 0; i < val.length; i++)
{
String your_string =val[i];
Pattern pattern = Pattern.compile("#");
String[] strarray =pattern.split(your_string);
for(int j=0;j<strarray.length;j++){
if(strarray[j].trim().length() >0){
System.out.println("arr"+j+"::" + strarray[j]);
}
else{
}
}
}

Convert Android Cursor to ArrayList of arrays

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.

Android: Create array of ROW_IDS from cursor - but how?

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

Categories

Resources