I tried to get contacts i saw that it need some time to wait. So, i tried to do it in async task with writting contacts to app db. Here is my failed attempt:
public class GetUpdateContactsTask extends AsyncTask<Void, Contact, Void> {
private static final String TAG = "lifeCycle";
private Context mContext;
public GetUpdateContactsTask (Context context){
mContext = context;
}
public interface OnFinishListener{
void onFinish();
}
public OnFinishListener finishListener;
public void setFinishListener(OnFinishListener finishListener){
this.finishListener = finishListener;
}
@Override
protected void onPreExecute() {
}
@Override
protected Void doInBackground(Void... params) {
ContentResolver cr = mContext.getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if (cur.getCount() > 0) { // here is an NullPointerException error
while (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()) {
String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Contact contact = new Contact();
contact.setName(name);
contact.setPhoneNumber(phoneNo);
publishProgress(contact);
}
pCur.close();
}
}
}
return null;
}
@Override
protected void onProgressUpdate(Contact... values) {
Contact contact = values[0];
String name = contact.getName();
String phoneNumber = contact.getPhoneNumber();
if (!phoneNumber.equals("not valid")){
Log.e(TAG, name + ": " + phoneNumber);
if(!DataHelper.getInstance().isContactIsset(values[0])){
DataHelper.getInstance().saveContact(values[0]);
Log.e(TAG, "contact saved");
} else {
Log.e(TAG, "contact is isset");
}
}
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
finishListener.onFinish();
}
}
it's not work. There is a nullpointerexception error on cursor. It will good if you help to correct my version, but it will great if you show your better solution. Thanks
Original posters solution incorrectly posted in question