魅族手机 Android5 获取手机联系人返回空指针

问题:

魅族手机 Android 版本号为5.1 调用手机通讯录选择联系人后 数据报空指针

这句报空指针,就是获取选择的联系人的id  再通过id去查询选择的电话号码和联系人的其他信息。

  long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

过程:

1.权限:

       安道理来说Android5的机器不需要动态申请权限,只需要在AndroidMainifest.xml文件中添加

    
    

就可以。但现实是在我手中的魅族手机添加后不起作用!可以跳到手机通信录页面,但返回不了数据!不报权限问题错误!

动态申请这两个权限也是通过的,但是手机上的权限显示状态是 询问

if (ActivityCompat.checkSelfPermission(MyhomePersonDialog.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED)

当手动把应用的权限改为允许后。就能正常返回联系人信息了。 所以悬疑是还需要其他权限。在上网查找后发现有需要添加

    

这个权限的说法。亲测我手里的魅族Android5手机没用。

2.替代

权限这个找遍了全网也没有提到过的。好在之前做过一个获取手机通讯录全部信息的功能,发现这个功能会主动弹出权限获取的弹窗提示。这个通过后 就可以正常的返回选择的联系人信息数据了。

魅族手机 Android5 获取手机联系人返回空指针_第1张图片

结果:

在跳转到手机通讯录页面选择联系人前  先调用:


private   final String[] PHONES_PROJECTION = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.Contacts.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};


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

让其弹出 权限询问  通过后再走正常逻辑就可以了。

后记:

这中做法实属无奈之举,如果有人知道这个问题有直接的解决方法。还望留言告知 谢谢;

后附全部代码:

 

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

 

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

 
public class MyhomePersonDialog extends BaseActivity   {
    private ImageView dialog_add_im;
    private   final String[] PHONES_PROJECTION = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.Contacts.Photo.PHOTO_ID, ContactsContract.CommonDataKinds.Phone.CONTACT_ID};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_wode_add);
        dialog_add_im = (ImageView) findViewById(R.id.dialog_add_im);
        dialog_add_im.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getPermission();
            }
        });
    }
    //一个联系人多号码选择弹窗
    private void showList(final String[] items) {
        new AlertDialog.Builder(this).setIcon(R.mipmap.ic_launcher)
                .setTitle("请选择:")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialog_add_et1.setText(items[i]);
                    }
                }).show();
    }

    //判断是否有获取联系人权限
    private void getPermission() {
        //检查 权限
        ArrayList permissions = new ArrayList<>();
        if (ActivityCompat.checkSelfPermission(MyhomePersonDialog.this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.READ_CONTACTS);
        }
        if (ActivityCompat.checkSelfPermission(MyhomePersonDialog.this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.GET_ACCOUNTS);
        }
        if (ActivityCompat.checkSelfPermission(MyhomePersonDialog.this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(Manifest.permission.READ_PHONE_STATE);
        }
        //判断
        if (permissions.size() == 0) {
            Cursor phoneCursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
            Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
            startActivityForResult(intent, 11);
            if(phoneCursor != null){
                phoneCursor.close();
            }
        } else {//没有权限,获取 权限
            ActivityCompat.requestPermissions(MyhomePersonDialog.this, permissions.toArray(new String[permissions.size()]), 2);
        }
    }



    //选择联系人返回信息
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            List list = new ArrayList();
            String NUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
            Uri URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            String id = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
            ContentResolver cr = getContentResolver();
            Uri contactData = data.getData();
            Cursor cursor = getContentResolver().query(contactData, null, null, null, null);
            cursor.moveToFirst();
            try {
                long contactId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                String username = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                dialog_add_et2.setText(username);
                Cursor phone = cr.query(URI, null, id + "=" + contactId, null, null);
                while (phone.moveToNext()) {
                    String usernumber = phone.getString(phone.getColumnIndex(NUM));
                    list.add(usernumber);
                }
                if (list.size() > 1) {
                    int size = list.size();
                    String[] array = new String[size];
                    for (int i = 0; i < list.size(); i++) {
                        array[i] = (String) list.get(i);
                    }
                    showList(array);
                } else {
                    dialog_add_et1.setText(list.get(0).toString());
                    System.out.println("aaa  e=" + list.get(0).toString());
                }
                cursor.close();
            } catch (Exception e) {
                System.out.println("aaa  e=" +e);
                Toast.makeText(this, "未同意获取权限,无法显示。", Toast.LENGTH_SHORT).show();
                try {
                    cursor.close();
                } catch (Exception a) {

                }
            }
        }
    }
    //申请权限返回监听
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 2:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, 11);
                } else {
                    Toast.makeText(this, "未同意获取权限,无法显示。", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}

 

你可能感兴趣的:(Android,android)