0

I tried this code to display the phone numbers in a checkbox within a listView:

@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main1);
   lv = (ListView) findViewById(R.id.contactList);

   Cursor numberCursor = null;
   Cursor peopleCursor = getContentResolver().query(ContactsContract
        .Contacts.CONTENT_URI,null,null
           ,null,null);  

   String [] nb = null ;
   String [] Tname = null;

   if(peopleCursor.getCount()>0)
   {  
       peopleCursor.moveToFirst();

       for(int i=0;i<peopleCursor.getCount();i++)
       {  
           //get number
           numberCursor=getContentResolver().query(ContactsContract
                .CommonDataKinds.Phone.CONTENT_URI, 
                new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}
                ,ContactsContract.CommonDataKinds.Phone._ID+"="+peopleCursor
                .getString(peopleCursor.getColumnIndex(ContactsContract.Contacts._ID)),  
                null,null);
           numberCursor.moveToFirst(); 

           String number=numberCursor.getString(numberCursor 
                  .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
           nb[i]=number;

           //get name
           String name=peopleCursor.getString(numberCursor
               .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Tname[i]=name;

           peopleCursor.moveToNext();                   
       }   

       SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,  
           R.layout.contact_entry, numberCursor,nb, 
           new int[] {R.id.checkBox});

           lv.setAdapter(adapter);

    }

} 

But I get this error in the logcat and I don't understand it --->

android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0  
Yury
  • 20,618
  • 7
  • 58
  • 86
Wael Ilahi
  • 41
  • 3

1 Answers1

0

Firstly, I think you should define size of nb and Tname before use them:

      String[] Tname  = new String[peopleCursor.getCount()];

      String[] nb = new String[numberCursor.getCount()];

But i think the problems is with each people in your contacts list may have one or more phone numbers. So, You should have two loops for peopleCursor and numberCursor. and your index (i in your code) should be used only for array Tname.

PhatHV
  • 8,010
  • 6
  • 31
  • 40
  • yes i define the size of nb and Tname but always the same error ----> "android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0" – Wael Ilahi Feb 24 '12 at 14:29