0

I am fetching data from database and after that assigning it to arrays in this process i always get length of all arrays as 1 only.

Method :

public void fetchData() {

    database.open();
    Cursor cursor = database.getAllData();
    cursor.moveToFirst();

    while (!(cursor.isAfterLast())) {
        nameArr = new String[] { cursor.getString(1) }; // i tried to put cursor data in arr from here
        addressArr = new String[] { cursor.getString(2) };
        contactArr = new String[]{ cursor.getString(3) };
        cursor.moveToNext();
    }

    database.close();
    Log.d("ArrayLength", Integer.toString(nameArr.length));//The arraylength is 1 i dont know why??

}
1
  • You're creating a new String array with only one element each time through the loop. Commented Sep 19, 2014 at 4:16

2 Answers 2

2

Use Cursor.getCount() outside while loop to initialize all arrays as:

 int count=cursor.getCount();
 nameArr=new String[count];
 addressArr=new String[count];
 contactArr=new String[count];
 int index_count=0;
while(!(cursor.isAfterLast())){
    nameArr[index_count]=cursor.getString(1); 
    addressArr[index_count]=cursor.getString(2);
    contactArr[index_count]=cursor.getString(3);
    index_count++;
    cursor.moveToNext();
}

To avoid use of index_count use ArrayList to store all data from cursor/

Sign up to request clarification or add additional context in comments.

Comments

0

This is a very simple example...

    Cursor client = db.rawQuery(sql, null);

    String[][] clients = new String[2][client.getCount()];
    if(client.moveToFirst()){
        do{
            clients[0][i] = client.getString(client.getColumnIndex(CLIENT_NAME));
            clients[1][i++] = String.valueOf(client.getInt(client.getColumnIndex(CLIENT_ID)));
        }while (client.moveToNext());
    }
    client.close();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.