我试图找到联系人,我看到它需要一些时间等待。因此,我尝试在将联系人写入应用程序数据库的异步任务中执行此操作。这是我失败的尝试:
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();
}
}
它不起作用。游标上存在nullpointerexception错误。如果您帮助更正我的版本会很好,但如果您展示更好的解决方案,它会很棒。感谢
答案 0 :(得分:1)
原始海报solution错误地发布了问题
问题出在联想安全应用中。它会阻止访问联系人。所以我将我的应用程序添加到白名单,问题解决了!
答案 1 :(得分:0)
您将从doInBackground
方法返回onProgressUpdate
并将结果输入return contact;
,而是用于更新进度状态,而不是
onPostExecute
然后在@Override
protected void onPostExecute(Contact values) {
super.onPostExecute(values);
Contact contact = values[0];
String name = contact.getName();
...............
...............
}
方法中获得结果,如下所示
{{1}}