【问题标题】:Problem saving contacts in text file using string使用字符串在文本文件中保存联系人时出现问题
【发布时间】:2019-02-25 13:19:55
【问题描述】:

此我的代码用于将联系人保存在外部存储目录中。但是这段代码在我打开手机上的Contact.txt文件时出现问题,手机上最后存储的电话号码记录在Contact.txt文件中。

private void getContactList() {
        ContentResolver cr = getContentResolver();
        Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
                null, null, null, null);
        String phoneNo = null;

        if ((cur != null ? cur.getCount() : 0) > 0) {
            while (cur != null && cur.moveToNext()) {

                String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                if (cur.getInt(cur.getColumnIndex(
                        ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
                    Cursor pCur = cr.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                            null,
                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
                            new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        phoneNo = pCur.getString(pCur.getColumnIndex(
                                ContactsContract.CommonDataKinds.Phone.NUMBER));
                        Log.i("TAG", "Name: " + name);
                        Log.i("TAG", "Phone Number: " + phoneNo);
                    }
                    pCur.close();

                    File root = new File(Environment.getExternalStorageDirectory(), "cache");

                    if (!root.exists())
                        root.mkdirs();

                    try {
                        File fileContact = new File(root, "Contact.txt");
                        FileWriter writer = new FileWriter(fileContact);
                        writer.append("Name: " + name + " - " + "Phone Number: " + phoneNo);
                        writer.flush();
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                    Log.i("TAG", "Game Over.");
                }
            }
        }
        if (cur != null) {
            cur.close();
        }
    }

【问题讨论】:

    标签: java android oop android-contacts


    【解决方案1】:

    您的手机在此处循环播放:

    while (pCur.moveToNext()) {
        phoneNo = pCur.getString(pCur.getColumnIndex(
                ContactsContract.CommonDataKinds.Phone.NUMBER));
        Log.i("TAG", "Name: " + name);
        Log.i("TAG", "Phone Number: " + phoneNo);
    }
    

    正在循环遍历所有联系人的电话,但是当循环退出时,phoneNo 将只包含最后一个电话,您需要将所有电话记录到 ArrayList 或类似的东西中,并将它们全部放在文件中。

    【讨论】:

      最近更新 更多