Информация о контактной информации из андроида возвращает исключение нулевого указателя

В моем коде Android

Я хочу получить контакт имя, адрес электронной почты и номер телефона как json, а затем хочу отобразить.

Вот мой код:

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:

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

ошибка, найденная в следующей строке кода:

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

Здесь я храню phonenumber и адрес электронной почты как array.Is там проблема инициализации массива?? любая идея ребята?

Ответ 1

Вы можете использовать этот подход для поиска контакта из списка контактов

 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;
    }

}

Ответ 2

Здесь:

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

NullPointerException вызвано тем, что phoneNumber null и не инициализирован.

Используйте Cursor. getCount(), чтобы инициализировать его как:

phoneNumber = new String[phoneCursor.getCount()];
phoneCursor.moveToFirst();
while (phoneCursor.moveToNext()) {
   //..your code here..              
 }

Ответ 3

Я думаю, вы должны исправить:

if (phoneCursor.movetoFirst()){
    while (!phoneCursor.isAfterLast()) {
        phoneNumber[p] = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
        p++;
        phoneCursor.movetoNext();
    }
}