【发布时间】:2017-05-25 15:08:41
【问题描述】:
我制作了一个应用程序,其中我需要电话簿中可用的所有联系人。我在列表中显示这些数字。应用程序工作正常,但有时应用程序强制关闭,因为光标返回 null。这并不总是发生,但有时会发生。现在我该如何处理????
代码
public static JSONArray getAllContactList(Context context) {
Cursor c = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
alAllContacts = new ArrayList<ContactModel>();
while (!(c == null) && c.moveToNext()) {
String id = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
String number = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
if (number.equalsIgnoreCase("1")) {
// Cursor phones = getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
// ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = '" + id + "'", null, null);
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id, null, null);
while (phones.moveToNext()) {
String contactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String contactNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactNumber = contactNumber.replace("+", "");
if (contactNumber.length() > 10) {
contactNumber = contactNumber.substring(2);
}
// contactNumber.replace("+91", "");
alAllContacts.add(new ContactModel(contactName, contactNumber));
//
}
}
}
c.close();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < alAllContacts.size(); i++) {
jsonArray.put(alAllContacts.get(i).getJSONObject());
}
return jsonArray;
}
logcat 说我在这一行得到空指针
while (phones.moveToNext()) {
有时我会因为对话框正在运行而强制关闭,所以我显示进度条的代码也是正确的
public static void showProgress(Context context, String msg, boolean isVisible) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(msg);
progressDialog.setCancelable(false);
}
if (isVisible) {
progressDialog.show();
} else if (isVisible == false) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
【问题讨论】:
-
请参考我的此链接以获取联系人stackoverflow.com/questions/19972085/…
-
@BhanuSharma 先生,我正在正确获取联系人,但有时我得到空指针,那么我该如何处理该空指针
-
如何处理空指针异常? while (phones != null && phones.moveToNext())
标签: android android-contacts android-progressbar