【问题标题】:Displaying the phone number of a contact in Android Contact Content Provider在 Android Contact Content Provider 中显示联系人的电话号码
【发布时间】:2015-04-14 20:03:37
【问题描述】:

我正在尝试编写一个程序来显示 android 中联系人的 id、姓名和电话号码。到目前为止,会显示联系人的 ID 和姓名,但不会显示联系人的号码。谁能帮帮我,下面是我的程序代码:

package com.example.oghenekaroedoh.provider;

import android.app.ListActivity;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.CursorAdapter;
import android.widget.SimpleCursorAdapter;

public class Provider2Activity extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_provider);

        Uri allContacts = ContactsContract.Contacts.CONTENT_URI;

        //query string for our contacts
        //Uri allContacts = Uri.parse("content://contacts/people");

        //declare our cursor
        Cursor c;

        String[] projection = new String[]
                {ContactsContract.Contacts._ID,
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.Contacts.HAS_PHONE_NUMBER};

        //---detect the android version
        //---Projection, Filtering, and sorting
        /* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
            controls how many columns are returned by the query; this parameter is known as the projection
           >>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
           enable you to specify a SQL WHERE clause to filter the result of the query
           >>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
           enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
        * */
        if (android.os.Build.VERSION.SDK_INT <11) {
            //---if the device ids running on OS before Honeycomb
            //use the managedQuery() of the Activity class to retrieve a managed cursor
            c = managedQuery(allContacts, projection, null, null, null);

        }
        else {
            //---Honeycomb and later use the cursor loader class to retrieve managed cursor---
            CursorLoader cursorLoader = new CursorLoader(
                    this,
                    allContacts,
                    projection,
                    null,
                    null ,
                    null);
            c = cursorLoader.loadInBackground();
        }

        //create columns for the contacts display name and the column
        String[] columns = new String[] {
                ContactsContract.Contacts.DISPLAY_NAME,
                ContactsContract.Contacts._ID};

        int[] views = new int[] {R.id.contactName, R.id.contactID};

        SimpleCursorAdapter adapter;

        //detect the android version again..s
        if (android.os.Build.VERSION.SDK_INT <11) {
            //---if it is before Honeycomb---
            //use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_provider, c, columns, views);
        }
        else {
            //---Honeycomb and later---
            ////use the SimpleCursorAdapter class to map the cursor to a view (like textViews imageViews e.t.c)
            //with an extra parameter known as CursorAdapter.FLAG_REGISTER_CURRENT_OBSERVER
            adapter = new SimpleCursorAdapter(
                    this, R.layout.activity_provider, c, columns, views,
                    CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
        }

        this.setListAdapter(adapter);
        PrintContacts(c);
    }

    private void PrintContacts(Cursor c)
    {
        //---display the contact id and name and phone number----
        if (c.moveToFirst()) {
            do{
                //---get the contact id and name
                String contactID = c.getString(c.getColumnIndex(
                        ContactsContract.Contacts._ID));
                String contactDisplayName =
                        c.getString(c.getColumnIndex(
                                ContactsContract.Contacts.DISPLAY_NAME));
                Log.v("Content Providers", contactID + ", " +
                        contactDisplayName);

                //---get phone number---
                int hasPhone =
                        c.getInt(c.getColumnIndex(
                                ContactsContract.Contacts.HAS_PHONE_NUMBER));
                if (hasPhone == 1) {
                    Cursor phoneCursor =
                            getContentResolver().query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
                            contactID, null, null);
                    while (phoneCursor.moveToNext()) {
                        Log.v("Content Providers",
                                phoneCursor.getString(
                                        phoneCursor.getColumnIndex(
                                                ContactsContract.CommonDataKinds.Phone.NUMBER)));
                    }
                    phoneCursor.close();
                }

            } while (c.moveToNext());
        }
    }

}

【问题讨论】:

    标签: android android-contentprovider android-contacts


    【解决方案1】:

    我通过添加扩展 ArrayAdapter 的 CustomAdapter MyClassAdapter 并填充 Contact 对象的 ArrayList 来使您的示例正常工作。

    import android.app.ListActivity;
    import android.content.ContentResolver;
    import android.content.Context;
    import android.content.CursorLoader;
    import android.database.Cursor;
    import android.net.Uri;
    import android.os.Bundle;
    import android.provider.ContactsContract;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.ArrayAdapter;
    import android.widget.TextView;
    
    import java.util.ArrayList;
    
    public class Provider2Activity extends ListActivity {
    
        ArrayList<Contact> contacts;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_provider2);
    
            contacts = new ArrayList<Contact>();
    
            Uri allContacts = ContactsContract.Contacts.CONTENT_URI;
    
            //declare our cursor
            Cursor c;
    
            String[] projection = new String[]
                    {ContactsContract.Contacts._ID,
                            ContactsContract.Contacts.DISPLAY_NAME,
                            ContactsContract.Contacts.HAS_PHONE_NUMBER};
    
    
            /* >>The second parameter of the managedQuery() method (third parameter for the CursorLoader class)
                controls how many columns are returned by the query; this parameter is known as the projection
               >>The third parameter of the managedQuery() method (fourth parameter for the CursorLoader class)
               enable you to specify a SQL WHERE clause to filter the result of the query
               >>The fourth parameter of the managedQuery() method (the fifth parameter for the CursorLoader class)
               enables you to specify a SQL ORDER BY clause to sort the result of the query, either in ascending or descending order
            * */
            if (android.os.Build.VERSION.SDK_INT <11) {
                //---if the device ids running on OS before Honeycomb
                //use the managedQuery() of the Activity class to retrieve a managed cursor
                c = managedQuery(allContacts, projection, null, null, null);
    
            }
            else {
                //---Honeycomb and later use the cursor loader class to retrieve managed cursor---
                CursorLoader cursorLoader = new CursorLoader(
                        this,
                        allContacts,
                        projection,
                        null,
                        null ,
                        null);
                c = cursorLoader.loadInBackground();
            }
    
            PrintContacts(c);
    
            MyClassAdapter adapter;
    
    
            //detect the android version again..
            if (android.os.Build.VERSION.SDK_INT <11) {
                //---if it is before Honeycomb---
    
                adapter = new MyClassAdapter(
                        this, R.layout.row_line, contacts);
            }
            else {
                //---Honeycomb and later---
    
                adapter = new MyClassAdapter(
                        this, R.layout.row_line, contacts);
            }
    
            this.setListAdapter(adapter);
    
        }
    
        private void PrintContacts(Cursor c)
        {
            ContentResolver cr = getContentResolver();
            //---display the contact id and name and phone number----
            if (c.moveToFirst()) {
                do{
                    //---get the contact id and name
                    String contactID = c.getString(c.getColumnIndex(
                            ContactsContract.Contacts._ID));
                    String contactDisplayName =
                            c.getString(c.getColumnIndex(
                                    ContactsContract.Contacts.DISPLAY_NAME));
                    Log.v("Content Providers", contactID + ", " +
                            contactDisplayName);
    
                    String contactDisplayPhone = "";
                        //---get phone number---
                    int hasPhone =
                            c.getInt(c.getColumnIndex(
                                    ContactsContract.Contacts.HAS_PHONE_NUMBER));
                    if (hasPhone == 1) {
                        Cursor phoneCursor =
                                getContentResolver().query(
                                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " +
                                                contactID, null, null);
                        while (phoneCursor.moveToNext()) {
                            Log.v("Content Providers",
                                    contactDisplayPhone = phoneCursor.getString(
                                            phoneCursor.getColumnIndex(
                                                    ContactsContract.CommonDataKinds.Phone.NUMBER)));
                        }
                        phoneCursor.close();
    
                    }
                    contacts.add(new Contact(contactDisplayName, contactID, contactDisplayPhone));
    
                } while (c.moveToNext());
            }
        }
    
        public class Contact{
            public String contactName = "";
            public String contactID = "";
            public String contactNumber = "";
            public Contact(String name, String id, String number){
    
                contactName = name;
                contactID = id;
                contactNumber = number;
            }
        }
    
        public class MyClassAdapter extends ArrayAdapter<Contact> {
    
            private class ViewHolder {
                private TextView name;
                private TextView id;
                private TextView number;
            }
    
            public MyClassAdapter(Context context, int textViewResourceId, ArrayList<Contact> items) {
                super(context, textViewResourceId, items);
            }
    
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;
                if (convertView == null) {
                    convertView = LayoutInflater.from(this.getContext())
                            .inflate(R.layout.row_line, parent, false);
    
                    viewHolder = new ViewHolder();
                    viewHolder.name = (TextView) convertView.findViewById(R.id.contactName);
                    viewHolder.id = (TextView) convertView.findViewById(R.id.contactID);
                    viewHolder.number = (TextView) convertView.findViewById(R.id.contactNumber);
    
                    convertView.setTag(viewHolder);
                } else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }
    
                Contact item = getItem(position);
                if (item!= null) {
                    viewHolder.name.setText(item.contactName);
                    viewHolder.id.setText(item.contactID);
                    viewHolder.number.setText(item.contactNumber);
                }
    
                return convertView;
            }
        }
    
    }
    

    row_line.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
    
        <TextView android:id="@+id/contactName"
            android:textSize="16sp"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <TextView android:id="@+id/contactID"
            android:textSize="16sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    
        <TextView android:id="@+id/contactNumber"
            android:textSize="16sp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    

    activity_provider2.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
        android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Provider2Activity">
    
        <ListView
    
            android:id="@android:id/list"
    
            android:layout_height="wrap_content"
    
            android:layout_width="match_parent">
    
        </ListView>
    
    </RelativeLayout>
    

    【讨论】:

    • 但是为什么非要创建一个单独的类来存储contactName、contactID和number,为什么不直接放在activity中呢
    • @AlexIrabor 之前,您直接使用来自Cursor 的数据,我无法将姓名、ID 和电话号码填充到单个Cursor 中,所以我决定添加自定义存储类和自定义适配器。这只是解决它的一种方法,但使用自定义适配器,您可以获得更大的灵活性。例如,您现在可以扩展功能并添加 ImageView 并在每个联系人旁边显示一张图片。
    • ..哦好的,再次感谢您..我刚刚发布了另一个问题,您可以帮我检查一下吗,它在我的个人资料中..当您在上面时,您可以投票赞成这个答案和问题。
    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 2012-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多