如何从联系人中获取联系人详细信息并在文本视图中显示?

时间:2014-04-14 09:48:39

标签: android

我想从联系人中获取联系人详细信息并在文本视图中显示。我尝试使用下面的代码,但我的应用程序崩溃了。我是android的初学者,我无法识别错误。任何人都可以帮助我.. 这是代码:                                    /MainActivity.java /

package com.example.retrievecontacts;

import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
    TextView txtv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtv = (TextView) findViewById(R.id.viewContacts);
        readContacts();

    }

    public void readContacts() {
        StringBuffer sb = new StringBuffer();
        sb.append("......Contact Details.....");
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, null);
        String name = null;
        String id = null;
        String phone = null;
        String emailContact = null;
        String emailType = null;
        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts._ID));
                name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            }
            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                System.out.println("name : " + name + ", ID : " + id);
                sb.append("\n Contact Name:" + name);
                Cursor pCur = cr.query(
                        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                + " = ?", new String[] { id }, null);
                while (pCur.moveToNext()) {
                    phone = pCur
                            .getString(pCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    sb.append("\n Phone number:" + phone);
                    System.out.println("phone" + phone);
                }
                pCur.close();
                Cursor emailCur = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                        null, ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                + " = ?", new String[] { id }, null);
                while (emailCur.moveToNext()) {
                    emailContact = emailCur
                            .getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                    emailType = emailCur
                            .getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                    sb.append("\nEmail:" + emailContact + "Email type:"
                            + emailType);
                    System.out.println("Email " + emailContact
                            + " Email Type : " + emailType);
                }
                emailCur.close();
            }
            sb.append("\n........................................");

        }
        txtv.setText(sb);
    }

}

                              /*activity.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"
    tools:context="com.example.retrievecontacts.MainActivity" >
 <TextView
     android:id="@+id/viewContacts"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_alignParentLeft="true"
     android:layout_alignParentTop="true"/>
 </RelativeLayout>

我还在清单中写了许可:

那么问题是什么。为什么我的应用程序崩溃了?

3 个答案:

答案 0 :(得分:2)

如果循环放在循环外面,如下所示。因此,当光标超过数据集中的最后一个条目时循环退出,因此当在if块中访问时它会崩溃。将if语句放在while循环中。

while (cur.moveToNext()) {
                id = cur.getString(cur
                        .getColumnIndex(ContactsContract.Contacts._ID));
                name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            }
            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {

答案 1 :(得分:1)

你忘记将光标移动到第一个位置:

cur.moveToFirst();

您的代码必须如下:

 if (cur.getCount() > 0) {
            cur.moveToFirst();
            while (cur.moveToNext()) {
             .......
             .......

如果这没有帮助您发布logcat错误。

我认为你必须得到CursorIndexOutOfBoundException

您还需要检查pCur

if (pCur.getCount() > 0) {
                pCur.moveToFirst();
                while (pCur.moveToNext()) {
                  .......
                  .......

emailCur以及您拥有的所有光标

你有另一个问题是 Manish Mulimani 在下面的回答中说,所以也读了

使用以下命令更改您的代码:

if (cur.moveToFirst()) {
                    do {

                                           // do your job 

                    } while (cur.moveToNext());

答案 2 :(得分:0)

我已经编写了这段代码来显示列表视图中存储在设备中的所有联系人姓名和号码....试试吧...它有效......

在列表视图中显示名称和号码的活动...

public class FirstActivity extends Activity {

ListView list;
ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String,String>>();


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

    list = (ListView) findViewById(R.id.list);


    Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);

    while(phones.moveToNext())
    {
        HashMap<String, String> nameNumberMap = new HashMap<String, String>();
        String contactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        nameNumberMap.put("Name",contactName);
        nameNumberMap.put("Number",contactNumber);
        al.add(nameNumberMap);

    }

    Log.e("check","as2");
    customAdapter adapter = new customAdapter(this, al);
    list.setAdapter(adapter);
    Log.e("check","as2"+al.size());



}
}

自定义适配器类

public class customAdapter extends BaseAdapter {

ArrayList<HashMap<String, String>> al = new ArrayList<HashMap<String,String>>();
Activity activity;
private static LayoutInflater inflater = null;

public customAdapter(Activity a, ArrayList<HashMap<String, String>> al) {
    Log.e("check", "");
    activity = a;
    this.al = al;
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    // TODO Auto-generated method stub
     return al.size();
}

@Override
public Object getItem(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    View vi=convertView;
    if(convertView==null)
    {
    vi = inflater.inflate(R.layout.row_layout, null);
    }
    TextView name = (TextView) vi.findViewById(R.id.Name);
    TextView number = (TextView) vi.findViewById(R.id.Number);

    HashMap<String, String> contains = new HashMap<String, String>();
    contains = al.get(position);
    Log.e("value check:----", contains.get("Name"));
    name.setText(contains.get("Name"));
    number.setText(contains.get("Number"));
    return vi;
}

}

首次活动的XML

<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".FirstActivity" 
android:orientation="vertical">

<ListView 
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>

</LinearLayout>

行布局的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/Name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30sp"
    />

    <TextView 
    android:id="@+id/Number"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    />

</LinearLayout>