Android获取联系人信息返回空指针异常 [英] android fetch contact information returns null pointer exception

查看:105
本文介绍了Android获取联系人信息返回空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的android代码中

In my android code

我想获取联系人的姓名,电子邮件和电话号码作为json,然后要显示.

I want to fetch contact's name,email and phone number as as json and then want to display.

这是我的代码:

public class MainActivity extends Activity {

    public TextView outputText;
    String[] phoneNumber;
    String[] email;
    String name;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        outputText = (TextView) findViewById(R.id.textView1);
        try {
            //fetchContacts();
            outputText.setText(fetchContacts());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public String fetchContacts() throws JSONException {

        Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
        String _ID = ContactsContract.Contacts._ID;
        String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
        String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;

        Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
        String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;

        Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
        String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
        String DATA = ContactsContract.CommonDataKinds.Email.DATA;

        ContentResolver contentResolver = getContentResolver();

        Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
                null);

        List<Contact> contacts = new ArrayList<Contact>();
        Gson gson = new Gson();

        // Loop for every contact in the phone
        if (cursor.getCount() > 0) {
            while (cursor.moveToNext()) {

                String contact_id = cursor
                        .getString(cursor.getColumnIndex(_ID));
                name = cursor.getString(cursor.getColumnIndex(DISPLAY_NAME));

                int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
                        .getColumnIndex(HAS_PHONE_NUMBER)));

                if (hasPhoneNumber > 0) {

                    int p = 0;
                    // Query and loop for every phone number of the contact
                    Cursor phoneCursor = contentResolver.query(
                            PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
                            new String[] { contact_id }, null);

                    while (phoneCursor.moveToNext()) {
                        phoneNumber[p] = phoneCursor.getString(phoneCursor
                                .getColumnIndex(NUMBER));
                        p++;
                    }
                    phoneCursor.close();

                    int q = 0;
                    // Query and loop for every email of the contact
                    Cursor emailCursor = contentResolver.query(
                            EmailCONTENT_URI, null, EmailCONTACT_ID + " = ?",
                            new String[] { contact_id }, null);

                    while (emailCursor.moveToNext()) {

                        email[q] = emailCursor.getString(emailCursor
                                .getColumnIndex(DATA));
                        q++;
                    }
                    emailCursor.close();

                    contacts.add(new Contact(name, phoneNumber, email));
                }
            }
        }
        return gson.toJson(contacts);
    }
}

但是我收到了nullpointer异常错误:

But I am getting nullpointer exception error :

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.contactdemo/com.example.contactdemo.MainActivity}: java.lang.NullPointerException

在以下代码行中发现

错误:

error found in below line of code:

phoneNumber[p] = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));

这里我将电话号码和电子邮件存储为数组,是否存在数组初始化问题?有想法的人吗?

Here I am storing phonenumber and email as array.Is there array initialization problem ?? any idea guys?

推荐答案

您可以使用这些方法从联系人列表中查找联系人

You can use these approach to finds the contact from contact list

 class FetchDeviceContact extends AsyncTask<Void, Integer, String>
    {
        protected void onPreExecute (){
            Constant.showProgressDialog(AddDeviceContactScreeen.this);
        }

        protected String doInBackground(Void...arg0) {


            arrayList.clear();


            ContentResolver cr = AddDeviceContactScreeen.this.getContentResolver();
            Cursor cur = AddDeviceContactScreeen.this.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

            while (cur.moveToNext()) {


                String id = cur.getString(cur.getColumnIndex(ContactsContract.Data._ID));

                String name = cur.getString(cur.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));

                String photoUri = cur.getString(cur.getColumnIndex(ContactsContract.Data.PHOTO_THUMBNAIL_URI));

                Bitmap my_btmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_up_blue);


                String email = null;
                String phoneNo = null;

                Cursor phonecur = AddDeviceContactScreeen.this.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                        new String[]{id}, null);


                if (photoUri != null) {
                    Uri my_contact_Uri = Uri.parse(photoUri);
                    try {

                        my_btmp = MediaStore.Images.Media.getBitmap(AddDeviceContactScreeen.this.getContentResolver(), my_contact_Uri);


                    } catch (FileNotFoundException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }


                if (phonecur.getCount() > 0) {


                    while (phonecur.moveToNext()) {


                        phoneNo = phonecur.getString(phonecur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));


                    }


                }

                Cursor emailCur = cr.query(
                        ContactsContract.CommonDataKinds.Email.CONTENT_URI, null,
                        ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                        new String[]{id}, null);

                while (emailCur.moveToNext()) {
                    // to get the contact names
//                = cur1.getString(cur1.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)
                    email = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));


                    if (email != null) {


                        System.out.println("Email============== :" + email);

                    }

                }
                emailCur.close();

                ContactBean bean = new ContactBean();

                bean.setName(name);
                bean.setEmail(email);
                bean.setImage(my_btmp);
                bean.setPhone_number(phoneNo);

                if (phoneNo == null || email == null) {

                } else {

                    arrayList.add(bean);
                }

            }

            return "";
        }

        protected void onProgressUpdate(Integer...a){

        }

        protected void onPostExecute(String result) {


            Constant.cancelDialog();



        }
    }


 new FetchDeviceContact().execute();

为其创建 getter setter 类:-

public class ContactBean {

    String name;
    String email;
    Bitmap image;
    String phone_number;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Bitmap getImage() {
        return image;
    }

    public void setImage(Bitmap image) {
        this.image = image;
    }

    public String getPhone_number() {
        return phone_number;
    }

    public void setPhone_number(String phone_number) {
        this.phone_number = phone_number;
    }

}

这篇关于Android获取联系人信息返回空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆