Saturday, July 28, 2012

Filling a ListView from a Cursor

check this out first :

now this works in the same way, it just picks up the data from a cursor as :

 String[] fromColumns={ContactsContract.Data.DISPLAY_NAME_PRIMARY};
        int[] toViews={R.id.name_entry};
     
        Cursor cursor = getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, null, null, null);
        //cursor.moveToFirst();
     
     
        SimpleCursorAdapter adapter=new SimpleCursorAdapter(this, R.layout.activity_cursoradapter, cursor, fromColumns, toViews,0);
        ListView listview=getListView();
       listview.setAdapter(adapter);
     
      // this.setListAdapter(adapter);

do not forget to add the permission in the manifest :

    <uses-permission android:name="android.permission.READ_CONTACTS" />


Additionaly, you may also implement click event for each item click :

 final OnItemClickListener mMessageClickedHandler = new OnItemClickListener(){
      @Override
      public void onItemClick(AdapterView parent, View v, int position, long id) {
      // TODO Auto-generated method stub
                  Toast.makeText(getApplicationContext(), position +" clicked", Toast.LENGTH_SHORT).show();
      }
           
             };
             listview.setOnItemClickListener(mMessageClickedHandler);
         
       }

No comments:

Post a Comment