Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android. to display contacts as list view

I want to display contacts in list view and add actions on all contacts , like on click on a particular contact it should display the phone number , mail id and delete of the particular contact...

import android.app.ListActivity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CPDemo1 extends ListActivity {


    @SuppressWarnings("unchecked")
 public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
     String str[]=    {"datta","vivek","Nagesh sir","shiv"};
     String name; 

        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        int nameIdx = cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);

        if (cursor.moveToFirst())


         do {

         int x = 0;

         name = cursor.getString(nameIdx);
         str[x]= name;
                 x++;
          ArrayAdapter arr = new ArrayAdapter(this, android.R.layout.simple_list_item_1,str);

          setListAdapter(arr);
 } while(cursor.moveToNext());

        }
like image 424
Datta Avatar asked Dec 13 '10 09:12

Datta


People also ask

How do I show my contact list on my Phone?

Open your Contacts app and tap the Options button (three dots), and select Contacts Manager. On the next screen, tap on Contacts to display from the menu. Next, if you only want contacts with a phone number, tap on Phone. You can also customize it by selecting just the Google account you want to see contacts from.


2 Answers

The problem in your current code is create new adapter for every loop. Just move ArrayAdapter arr = new ArrayAdapter(this, android.R.layout.simple_list_item_1,str); out of do while loop. And another issue, You work too much on UIThread (loop through cursor )so user will see a black screen or ANR if your numbers of contact is huge. Learn to use AsyncQueryHandler and CursorAdapter, it's all in my link and nikki's link

And why don't you have a look at default Contacts app in Android source code: Below is my custom Contacts App.enter image description here

https://github.com/android/platform_packages_apps_contacts

like image 152
Trung Nguyen Avatar answered Oct 11 '22 12:10

Trung Nguyen


Just have a look at below link and try using this code for displaying contacts saved in android phone book into your application.

http://developer.android.com/resources/samples/ContactManager/index.html

like image 20
Nikki Avatar answered Oct 11 '22 12:10

Nikki