我对Android开发相对较新,目前我需要你的帮助。在某些设备中,我的代码似乎运行良好,没有显示具有相同电话号码的联系人(简单ListView
的联系人姓名和号码)。但当我尝试使用其他设备时,我开始注意到所有联系人都是重复的,具有相同的电话号码,但数字格式不同。
例如,联系人姓名 Ana 将在ListView
两次显示,其中数字 09876543210 和 0987 654 3210 。
我试着到处搜索,但我找不到适合我目前情况的任何解决方案。我找到的所有解决方案都显示了已弃用且过时的代码(未使用CursorLoader
,使用已弃用的Contacts
代替ContactsContract
)。我认为答案在于ContactsContract
表,但我对此并不了解。
以下是我的代码的副本:
public class ContactsTab extends ListFragment
implements LoaderCallbacks<Cursor> {
ListView mContactsList;
// Defines an array from cursor column...
private static final String[] fromColumns = {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
// ...to views/rows (id)
private static final int[] toViews = {
R.id.contactName,
R.id.contactNumber
};
// An adapter that binds the result Cursor to the ListView
private ContactsSimpleCursorAdapter mCursorAdapter;
// These are the contact rows to retrieve
private static final String[] PROJECTION = {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER
};
// This is the select criteria
private static final String SELECTION =
"((" + ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " NOTNULL) AND ("
+ ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " != ' ') AND ("
+ ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER + " = 1))";
private static final int PERMISSIONS_REQUEST_READ_CONTACTS = 1;
private static final int PERMISSIONS_REQUEST_CALL_PHONE = 2;
private boolean mContactsPermissionGranted;
private boolean mCallPermissionGranted;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_contacts, container, false);
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Gets cursor adapter
mCursorAdapter = new ContactsSimpleCursorAdapter(
getActivity(),
R.layout.contact_item_view,
null,
fromColumns,
toViews,
0);
// Gets the ListView
mContactsList = (ListView) getActivity().findViewById(android.R.id.list);
// Sets the adapter for the ListView
mContactsList.setAdapter(mCursorAdapter);
getLoaderManager().initLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
// starts the query
return new CursorLoader(
getActivity(),
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PROJECTION,
SELECTION,
null,
ContactsContract.Contacts.SORT_KEY_PRIMARY + " ASC"
);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
mCursorAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mCursorAdapter.swapCursor(null);
}
}
非常感谢你的帮助。