0

我希望在单击按钮时弹出一个可滚动的联系人列表。我无法弄清楚如何获取它以及内容解析器、托管查询和适配器​​如何工作。

我尝试过使用以下代码:

package com.hapybay.rad;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.database.Cursor;

public class startingPoint extends Activity {
    Button redcandle;
    private ListView mContactList;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /*Obtain handles to UI objects (Constructor)*/
        redcandle = (Button) findViewById(R.id.button1);

        /*Register handle for UI element*/
        redcandle.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                populateContactList();
            }
        });
    }

    private void populateContactList() {
        // Build adapter with contact entries
        Cursor cursor = getContacts();
        String[] fields = new String[] {
                ContactsContract.Data.DISPLAY_NAME
        };
        SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.contact_entry,   cursor,
                fields, new int[]{R.id.contactEntryText});
        mContactList.setAdapter(adapter);
    }

    private Cursor getContacts()
    {
        // Run query
        Uri uri = ContactsContract.Contacts.CONTENT_URI;
        String[] projection = new String[] {
                ContactsContract.Contacts.LOOKUP_KEY,
                ContactsContract.Contacts.DISPLAY_NAME };
        String selection = null;
        String[] selectionArgs = null;
        String sortOrder = null;

        return managedQuery(uri, projection, selection, selectionArgs, sortOrder);
    }
}
4

1 回答 1

0
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);

并在您的活动中覆盖它

public void onActivityResult(int reqCode, int resultCode, Intent data) {
  super.onActivityResult(reqCode, resultCode, data);

  switch (reqCode) {
    case (PICK_CONTACT) :
      if (resultCode == Activity.RESULT_OK) {
        Uri contactData = data.getData();
        Cursor c =  managedQuery(contactData, null, null, null, null);
        if (c.moveToFirst()) {
          String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
          // TODO Whatever you want to do with the selected contact name.
        }
      }
      break;
  }
}

不要忘记添加权限

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

于 2012-07-19T10:18:01.690 回答