此“我的代码”,用于在外部存储目录中保存联系人。但是,当我打开手机上的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();
}
}
答案 0 :(得分:2)
您的电话在这里循环
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或类似的东西中,并将它们全部放入文件中