码迷,mamicode.com
首页 > 移动开发 > 详细

android 获取联系人的姓名和电话,无法获取电话

时间:2014-10-20 23:16:54      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:des   android   io   os   ar   java   for   sp   数据   

============问题描述============


代码如下
package com.example.sysaction;



import android.net.Uri;

import android.os.Build;

import android.os.Bundle;

import android.provider.ContactsContract;

import android.annotation.SuppressLint;

import android.annotation.TargetApi;

import android.app.Activity;

import android.content.CursorLoader;

import android.content.Intent;

import android.database.Cursor;

import android.view.Menu;

import android.view.View;

import android.view.View.OnClickListener;

import android.widget.Button;

import android.widget.EditText;



public class SysAction extends Activity {



	final int PICK_CONTACT = 0;

	@Override

	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.main);

		

		Button bn = (Button)findViewById(R.id.bn);

		bn.setOnClickListener(new OnClickListener(){

			@Override

			public void onClick(View v) {

				// TODO Auto-generated method stub

				Intent intent = new Intent();

				intent.setAction(Intent.ACTION_GET_CONTENT);

				intent.setType("vnd.android.cursor.item/phone");

				startActivityForResult(intent,PICK_CONTACT);

			}

		});

	}



	@TargetApi(Build.VERSION_CODES.HONEYCOMB)

	@SuppressLint("NewApi")

	public void onActivityResult(int requestCode, int resultCode, Intent data)

	{

		super.onActivityResult(requestCode, resultCode, data);

		switch(requestCode)

		{

		case(PICK_CONTACT):

			if(resultCode == Activity.RESULT_OK)

			{

				Uri contactData = data.getData();

				CursorLoader cursorLoader = new CursorLoader(this, contactData, null, null, null, null);

				Cursor cursor =cursorLoader.loadInBackground();

				

				if(cursor.moveToFirst())

				{

					String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

					String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));

					String phoneNumber = "此联系人暂未输入电话号码";

					Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +"="+contactId, null, null);

					

					if(phones.moveToFirst())

					{

						phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

					}

					

					phones.close();

					EditText show = (EditText)findViewById(R.id.show);

					show.setText(name);

					EditText phone = (EditText)findViewById(R.id.phone);

					phone.setText(phoneNumber);

				}

				cursor.close();

			}

		break;

		

		}

	}



}



ContactsContract.CommonDataKinds.Phone.CONTACT_ID 返回的值为null

============解决方案1============


引用 3 楼 bdmh 的回复:
不是所有的都能拿到,由于移动运营商没有把手机号码的数据写入到sim卡中


你这是从外星来的吗

============解决方案2============




intent.setType("vnd.android.cursor.item/phone");


改成

intent.setType("vnd.android.cursor.item/phone_v2");


然后去掉重复创建的cursor。
代码如下:

public class SysAction extends Activity {

	 

    final int PICK_CONTACT = 0;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_sys_action);

         

        Button bn = (Button)findViewById(R.id.bn);

        bn.setOnClickListener(new OnClickListener(){

            @Override

            public void onClick(View v) {

                // TODO Auto-generated method stub

                Intent intent = new Intent();

                intent.setAction(Intent.ACTION_GET_CONTENT);

                intent.setType("vnd.android.cursor.item/phone_v2");

                startActivityForResult(intent,PICK_CONTACT);

            }

        });

    }

 

    @TargetApi(Build.VERSION_CODES.HONEYCOMB)

    @SuppressLint("NewApi")

    public void onActivityResult(int requestCode, int resultCode, Intent data)

    {

        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode)

        {

        case(PICK_CONTACT):

            if(resultCode == Activity.RESULT_OK)

            {

                Uri contactData = data.getData();

                CursorLoader cursorLoader = new CursorLoader(this, contactData, null, null, null, null);

                Cursor cursor =cursorLoader.loadInBackground();

                if (cursor.moveToFirst())

                {

                    String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

                    String phoneNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                    EditText show = (EditText)findViewById(R.id.show);

                    show.setText(name);

                    EditText phone = (EditText)findViewById(R.id.phone);

                    phone.setText(phoneNumber);

                }

                cursor.close();

            }

        break;

         

        }

    }

}

============解决方案3============


这样:
/**读取通讯录异步Handler*/
private AsyncQueryHandler asyncQuery;
/**
 * 读取通讯录
 */
private void readContacts(){
asyncQuery = new ContactAsyncQueryHandler(getContentResolver());
Uri uri = Uri.parse("content://com.android.contacts/data/phones");    
        String[] projection = { "_id", "display_name", "data1", "sort_key" };    
        asyncQuery.startQuery(0, null, uri, projection, null, null,    
                "sort_key COLLATE LOCALIZED asc");
}

//异步查询联系人  
    private class ContactAsyncQueryHandler extends AsyncQueryHandler {    
    
        public ContactAsyncQueryHandler(ContentResolver cr) {    
            super(cr);    
        }    
    
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {    
            if (cursor != null && cursor.getCount() > 0) {    
             ArrayList<CallsItem> list = new ArrayList<CallsItem>();
                cursor.moveToFirst();    
                for (int i = 0; i < cursor.getCount(); i++) {  
                 CallsItem item = new CallsItem();    
                    cursor.moveToPosition(i);    
                    String name = cursor.getString(1);    
                    String number = cursor.getString(2);    
                    String sortKey = cursor.getString(3);  
                    if (number.startsWith("+86")) {    
                        number = number.substring(3); //去掉+86   
                    }
                    item.name = name;
                    item.number = number;
                    item.sort = sortKey;
                    list.add(item);
//                    System.out.println("name:" + name + " number:" + number + " sort:" + sortKey);
                }
                app.allList = list;
            }    
        }    
    }

android 获取联系人的姓名和电话,无法获取电话

标签:des   android   io   os   ar   java   for   sp   数据   

原文地址:http://www.cnblogs.com/lmyangbk/p/4038767.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!