光标错误,从电话联系人列表中获取电话联系人

Posted

技术标签:

【中文标题】光标错误,从电话联系人列表中获取电话联系人【英文标题】:Cursor Error, Getting phone contact from phone contact list 【发布时间】:2015-12-16 01:45:26 【问题描述】:

我知道有很多关于如何从联系人列表中选择电话联系人的答案,我从过去 2 小时开始就一直在研究它们。我的片段中有 onActivityResult() 代码但是在查询 uri 时我不断收到此光标错误。请看一下

package zafus.addressbook;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;


/**
 * A simple @link Fragment subclass.
 * Activities that contain this fragment must implement the
 * @link //ContactAddressEntryFragment.//OnFragmentInteractionListener interface
 * to handle interaction events.
 * Use the @link ContactAddressEntryFragment#newInstance factory method to
 * create an instance of this fragment.
 */
public class ContactAddressEntryFragment extends Fragment 
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private final int PICK_CONTACT=1;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment ContactAddressEntryFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static ContactAddressEntryFragment newInstance(String param1, String param2) 
        ContactAddressEntryFragment fragment = new ContactAddressEntryFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    

    public ContactAddressEntryFragment() 
        // Required empty public constructor
    

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        if (getArguments() != null) 
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        
    
    private View row;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) 
        // Inflate the layout for this fragment
        row=inflater.inflate(R.layout.fragment_contact_address_entry, container, false);

        TextView ch1=(TextView)row.findViewById(R.id.NotInContactCheckBox);
        ch1.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                    LinearLayout l=(LinearLayout)row.findViewById(R.id.select_from_contacts_button_LinearLayout);
                    l.setVisibility(View.GONE);
                    RelativeLayout r=(RelativeLayout)row.findViewById(R.id.random);
                    r.setVisibility(View.VISIBLE);
                    l=(LinearLayout)row.findViewById(R.id.select_from_IN_contacts_button_LinearLayout);
                    l.setVisibility(View.VISIBLE);
                

        );


        ch1=(TextView)row.findViewById(R.id.InContactCheckBox);

        ch1.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                    LinearLayout l=(LinearLayout)row.findViewById(R.id.select_from_contacts_button_LinearLayout);
                    l.setVisibility(View.VISIBLE);
                    RelativeLayout r=(RelativeLayout)row.findViewById(R.id.random);
                    r.setVisibility(View.GONE);
                    l=(LinearLayout)row.findViewById(R.id.select_from_IN_contacts_button_LinearLayout);
                    l.setVisibility(View.GONE);

            
        );

        Button b=(Button)row.findViewById(R.id.select_from_contacts_button);
        b.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View v) 
                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
                startActivityForResult(intent, PICK_CONTACT);
            
        );


        return row;
    



    @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) 
        super.onActivityResult(reqCode, resultCode, data);

        Toast.makeText(getActivity(),"OnResult fragment called",Toast.LENGTH_LONG).show();
        Uri contactData = data.getData();
        switch (reqCode) 
            case PICK_CONTACT:
                if (resultCode == Activity.RESULT_OK) 
                    Cursor cursor = getActivity().getContentResolver().query(contactData, null, null, null, null);
                    try 
                        int contactIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID);
                        int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                        int phoneNumberIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                        int photoIdIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_ID);
                        int emailIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.ADDRESS);
                        cursor.moveToFirst();
                        String name="";String phoneNumber="";String emailAddress="";

                        //phoneNumber =       cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        //name =              cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        //emailAddress =              cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Email.ADDRESS));
                        do 
                            String idContact = cursor.getString(contactIdIdx);
                            name = cursor.getString(nameIdx);
                            phoneNumber = cursor.getString(phoneNumberIdx);
                            emailAddress=cursor.getString(emailIdx);
                         while (cursor.moveToNext());
                        setData(name,phoneNumber,emailAddress);
                     catch (Exception e) 
                        e.printStackTrace();
                        Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_LONG).show();
                     finally 
                        if (cursor != null) 
                            cursor.close();
                        
                    
                
                break;
        
    


public void setData(String n,String p,String e)
   // CheckBox ch=(CheckBox)row.findViewById(R.id.InContactCheckBox);
    LinearLayout l=(LinearLayout)row.findViewById(R.id.select_from_contacts_button_LinearLayout);
    //ch.setChecked(false);
    l.setVisibility(View.GONE);
    RelativeLayout r=(RelativeLayout)row.findViewById(R.id.random);
    r.setVisibility(View.VISIBLE);
    l=(LinearLayout)row.findViewById(R.id.select_from_IN_contacts_button_LinearLayout);
    l.setVisibility(View.VISIBLE);


    EditText editText = (EditText)row.findViewById(R.id.contact_address_name_entry);
    editText.setText(n, TextView.BufferType.EDITABLE);

    editText = (EditText)row.findViewById(R.id.contact_address_number_entry);
    editText.setText(p, TextView.BufferType.EDITABLE);

    editText = (EditText)row.findViewById(R.id.contact_address_email_entry);
    editText.setText(e, TextView.BufferType.EDITABLE);




    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) 
        if (mListener != null) 
           // mListener.onFragmentInteraction(uri);
        
    

    @Override
    public void onAttach(Activity activity) 
        super.onAttach(activity);
        try 
            mListener = (OnFragmentInteractionListener) activity;
         catch (ClassCastException e) 
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        
    

    @Override
    public void onDetach() 
        super.onDetach();
        mListener = null;
    

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    /*public interface OnFragmentInteractionListener 
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    */


这是错误的内容:

【问题讨论】:

【参考方案1】:

我想从电话联系人列表(片段内)中获取所选联系人的联系人姓名、号码和电子邮件地址。

这就是你创建意图的方式

Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);

startActivityForResult(intent, PICK_CONTACT);

在哪里:private final int PICK_CONTACT=1;

OnActivtyResult 在下面

 @Override
    public void onActivityResult(int reqCode, int resultCode, Intent data) 
        super.onActivityResult(reqCode, resultCode, data);

        Toast.makeText(getActivity(),"OnResult fragment called",Toast.LENGTH_LONG).show();
        Uri contactData=ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        if(data!=null) 
             contactData = data.getData();
        
        switch (reqCode) 
            case PICK_CONTACT:
                if (resultCode == Activity.RESULT_OK) 
                    Cursor c = getActivity().getContentResolver().query(contactData, null, null, null, null);
                    String name="",email="",number="";
                    if (c.moveToFirst()) 


                        String id =c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));

                        String hasPhone =c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                        //String hasEmail =c.getString(c.getColumnIndex(ContactsContract.Contacts.Data.DATA1.));


                        if (hasPhone.equalsIgnoreCase("1")) 
                            Cursor phones = getActivity().getContentResolver().query(
                                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
                                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                                    null, null);
                            phones.moveToFirst();
                            number = phones.getString(phones.getColumnIndex("data1"));
                            phones.close();
                        

                        Cursor emailCur = getActivity().getContentResolver().query(
                                ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                                new String[]id, null);
                        while (emailCur.moveToNext()) 
                            // This would allow you get several email addresses
                            // if the email addresses were stored in an array
                            if(emailCur.getString(
                                    emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))!="")
                            email = emailCur.getString(
                                    emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
                            String emailType = emailCur.getString(
                                    emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
                        
                        emailCur.close();
                        name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        c.close();
                    

                    setData(name,number,email);
                    // Do something with the phone number...
                    
                

        

不要忘记在父 Activity 中添加它

 @Override
        public void onActivityResult(int reqCode, int resultCode, Intent data) 
            super.onActivityResult(reqCode, resultCode, data);
        

【讨论】:

以上是关于光标错误,从电话联系人列表中获取电话联系人的主要内容,如果未能解决你的问题,请参考以下文章

Android从联系人列表中获取电话号码

从 Android 联系人中获取电子邮件和电话

获取 Android 联系人光标异常

从联系人 Android 中获取一个电话号码

从 Android 中的 URI 检索联系人电话号码

通过 ID 获取联系电话号码 - 空光标