使用字符串在文本文件中保存联系人时出现问题

Problem saving contacts in text file using string

我的代码用于在外部存储目录中保存联系人。但是当我打开我的phone上的Contact.txt文件时,这段代码是有问题的,phone上存储的最后一个phone号码记录在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();
        }
    }

你的 phone 在这里循环:

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

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