所以,我有我的数据库表(sql或mysql):
用户表字段: - idPhoneNumber - 姓名
我的应用程序需要从联系人列表中加载所有电话号码,检查db中是否存在该号码,然后保存在列表中或插入到sqlite中。
其实我的代码是这样的:
private void getContact() {
List<String> contacts = new ArrayList<>();
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
assert cursor != null;
if (cursor.moveToFirst()) {
do {
if(cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ id,null, null);
assert phones != null;
phones.moveToNext();
// int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
if(phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE) == ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE) {
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
phoneNumber = phoneNumber.replace("-", "").trim().replaceAll(" ", "");
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
/* HERE */
checkcontactThread(phoneNumber); // ????
contacts.add(name);
}
phones.close();
}
} while (cursor.moveToNext());
}
cursor.close();
// ***so here i should update my SQLITE with all contacts in my list 'contacts'.***
return contacts;
}
这样做的最佳做法是什么?我使用齐射来向我的http服务器发出请求。如果我想使用它,我在“getContact”中想到这样的东西
已编辑:
private void checkcontactThread(final String phoneNumber) {
Log.e("TagFriends", "Checking: "+phoneNumber);
StringRequest stringRequest = new StringRequest(Request.Method.PUT,
"URL/SERVER", new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// so here i should add my contact if response = true ?
}
},new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phoneNumber", phoneNumber);
return params;
}
};
app.addRequest(stringRequest);
}
请记住,如果存在于DB中,我必须检查每个号码的编号。
如果我的联系人列表中有100个号码,那么我必须做100个请求吗?