Android获取频繁的ContactList

时间:2014-11-12 10:35:34

标签: android contacts

我正在尝试频繁调用列表。 CONTENT_STREQUENT_URI为您提供星标和频繁,我只是经常想要。 知道我为什么会收到错误吗?

代码:

    String selection = Contacts.STARRED + "=?";
    String[] selectionArgs = new String[1];
    selectionArgs[0] = "0";
    Cursor  c = this.getContentResolver (). query (Contacts.CONTENT_STREQUENT_URI,
            null, selection, selectionArgs,null);   
    if (c != null) {
        c.moveToFirst();
        do {
                System.out.println(" " + c);

        }while (c.moveToNext());
    }

目录下载:

11-12 10:13:36.615: E/AndroidRuntime(25592): FATAL EXCEPTION: main
11-12 10:13:36.615: E/AndroidRuntime(25592): Process: com.hanstiger.android.pric, PID: 25592
11-12 10:13:36.615: E/AndroidRuntime(25592): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.hanstiger.android.pric/com.hanstiger.android.pric.setting.Setting}: java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 1 parameters.
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2224)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2283)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread.access$800(ActivityThread.java:144)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.os.Handler.dispatchMessage(Handler.java:102)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.os.Looper.loop(Looper.java:136)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread.main(ActivityThread.java:5153)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at java.lang.reflect.Method.invokeNative(Native Method)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at java.lang.reflect.Method.invoke(Method.java:515)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:732)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at dalvik.system.NativeStart.main(Native Method)
11-12 10:13:36.615: E/AndroidRuntime(25592): Caused by: java.lang.IllegalArgumentException: Cannot bind argument at index 2 because the index is out of range.  The statement has 1 parameters.
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:167)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:137)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.content.ContentProviderProxy.query(ContentProviderNative.java:420)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.content.ContentResolver.query(ContentResolver.java:461)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.content.ContentResolver.query(ContentResolver.java:404)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at com.hanstiger.android.pric.setting.Setting.onCreate(Setting.java:62)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.Activity.performCreate(Activity.java:5322)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
11-12 10:13:36.615: E/AndroidRuntime(25592):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2181)

1 个答案:

答案 0 :(得分:0)

第1步:创建活动

public class MainActivity extends Activity {

ListView outputText;
List<String> userName;
Map<String, String> userNamePhno;
Map<String, String> userNameEmail;
StringBuffer output;
CustomAdapter adapter;
Dialog dialogDetails;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    outputText = (ListView) findViewById(R.id.listview);

    userNameEmail = new HashMap<String, String>();
    userNamePhno = new HashMap<String, String>();
    userName = new ArrayList<String>();

    new getContacts().execute();
    outputText.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {

            String[] details = new String[] { userName.get(arg2),
                    userNamePhno.get(userName.get(arg2)),
                    userNameEmail.get(userName.get(arg2)) };
            dialogDetails = new Dialog(MainActivity.this);
            dialogDetails.setContentView(R.layout.contact_details);
            dialogDetails.setTitle("Details");
            dialogDetails.show();

            TextView tvName = (TextView) dialogDetails.findViewById(R.id.name);
            TextView tvNumber = (TextView) dialogDetails.findViewById(R.id.phno);
            TextView tvEmail = (TextView) dialogDetails.findViewById(R.id.email);
            if (details[1]==null) 
            {
                tvName.setText(details[0]);
                tvNumber.setText("-");
                tvEmail.setText(details[2]);
            }
            else if (details[2]==null) 
            {
                tvName.setText(details[0]);
                tvNumber.setText(details[1]);
                tvEmail.setText("-");
            } 
            else if (details[2]==null && details[1]==null) 
            {

                tvName.setText(details[0]);
                tvNumber.setText("-");
                tvEmail.setText("-");
            } 
            else 
            {
                tvName.setText(details[0]);
                tvNumber.setText(details[1]);
                tvEmail.setText(details[2]);
            }

        }
    });

}

public class getContacts extends AsyncTask<Void, Void, Void> {
    ProgressDialog dialog;

    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(MainActivity.this);
        dialog.setCancelable(false);
        dialog.setMessage("Wait please");
        dialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
        fetchContacts();

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        dialog.dismiss();
        dialog.setCancelable(true);
        adapter = new CustomAdapter(MainActivity.this, userName,
                userNamePhno);
        outputText.setAdapter(adapter);
    }
}

private void fetchContacts() {
    String phoneNumber = null;
    String email = null;

    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;

    output = new StringBuffer();

    ContentResolver contentResolver = getContentResolver();

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

    if (cursor.getCount() > 0) {

        while (cursor.moveToNext()) {

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

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

            if (hasPhoneNumber > 0) {
                output.append("\n First Name:" + name);
                userName.add(name);

                // 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 = phoneCursor.getString(phoneCursor
                            .getColumnIndex(NUMBER));
                    output.append("\n Phone number:" + phoneNumber);
                    // userPhoneNumber.add(phoneNumber);
                    userNamePhno.put(name, phoneNumber);

                }
                phoneCursor.close();

                // 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 = emailCursor.getString(emailCursor
                            .getColumnIndex(DATA));
                    output.append("\nEmail:" + email);
                    // userEmailAddress.add(email);
                    userNameEmail.put(name, email);

                }
                emailCursor.close();

            }
            output.append("\n");

        }
        // outputText.setText(output);

    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

第2步:创建适配器

public class CustomAdapter extends ArrayAdapter<String> {
private Activity context;
private List<String> userName;
private Map<String, String> userNamePhno;
/*private List<String> userPhoneNumber;
private List<String> userEmailAddress;*/

public CustomAdapter(MainActivity mainActivity, List<String> userName, Map<String, String> userNamePhno) {
    super(mainActivity, R.layout.list_row, userName);
    this.context=mainActivity;
    this.userName = userName;
    this.userNamePhno=userNamePhno;
    /*this.userPhoneNumber = userPhoneNumber;
    this.userEmailAddress = userEmailAddress;*/

}
static class ViewHolder {
    public TextView userName;
    public TextView userNumber;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    if(vi == null){

        LayoutInflater inflater = context.getLayoutInflater();
        vi = inflater.inflate(R.layout.list_row, null);
        ViewHolder holder = new ViewHolder();
        holder.userName=(TextView) vi.findViewById(R.id.contact_name);
        holder.userNumber=(TextView) vi.findViewById(R.id.contact_number);
        vi.setTag(holder);
    }
    ViewHolder holder = (ViewHolder) vi.getTag();
    holder.userName.setText("Name: "+userName.get(position).toUpperCase());
    holder.userNumber.setText("Ph No: "+userNamePhno.get(userName.get(position)));
    return vi;
}

}

如有任何疑问,请随时询问。