使用异步任务修改联系人列表视图中的元素

Use async task to modify element in a contact listview

我想检查我的联系人的电话号码是否在数据库中。

到目前为止,我使用自定义适配器创建了一个列表视图,可以显示联系人姓名、号码和图像。我添加了第四个字段,如果电话号码在数据库中,它应该显示。

我使用 asynctask 来获得一个 json 这样的 {"android":{"error":"0"}} 以防数字在数据库中并且 {"android":{"error":"1"}} 如果没有。

我的问题是如何将电话号码传递给 asynctask 以及 asynctask 应该做什么 return 以便可以将 textview 设置为显示 "ok".

我一共使用的代码class。

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class contactos extends Activity {

ListView lv_addcontacts;
Cursor cur;
ContentResolver cr;

JSONArray android = null;
JSONParser jsonParser = new JSONParser();
private static String url = "my.php";
private static final String TAG_OS = "android";
private static final String TAG_ERROR = "error";

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.contactos);
    readContacts();

    if (!((cur.moveToFirst()) || cur.equals(null) || cur.getCount() == 0)) {

    } else if (cur.getCount() > 0) {
        cur.moveToFirst();
    }

    lv_addcontacts = (ListView) findViewById(R.id.lv_addcontact);

    CustomAdapterAddContacts myad = new CustomAdapterAddContacts();

    lv_addcontacts.setAdapter(myad);

}



class CustomAdapterAddContacts extends BaseAdapter {

    @Override
    public int getCount() {

        System.out.println(cur.getCount());

        return cur.getCount();
    }

    @Override
    public Object getItem(int position) {

        return position;
    }

    @Override
    public long getItemId(int position) {

        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {


        ContactViewHolder contactViewHolder;

        if (convertView == null) {

            // Inflate the layout
            LayoutInflater li = getLayoutInflater();
            convertView = li.inflate(
                    R.layout.contactos_detalle, null);

            contactViewHolder = new ContactViewHolder();

            contactViewHolder.imgContact = (ImageView) convertView
                    .findViewById(R.id.imgView_addcontact);
            contactViewHolder.txtViewContactName = (TextView) convertView
                    .findViewById(R.id.txtView_addcontact_contactname);
            contactViewHolder.txtViewPhoneNumber = (TextView) convertView
                    .findViewById(R.id.txtview_addcontact_phonenumber);
            contactViewHolder.txtViewCheck = (TextView) convertView
                    .findViewById(R.id.txtview_addcontact_check);

            convertView.setTag(contactViewHolder);
        } else {
            contactViewHolder = (ContactViewHolder) convertView.getTag();
        }

            cur.moveToPosition(position);

            // Add Contact Name //

            String name = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));

            if (name != null)
                contactViewHolder.txtViewContactName.setText(name);
            else
                contactViewHolder.txtViewContactName.setText("Unknown");

            // Add Phone Number //

            String phoneNumber = cur
                    .getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

            if (phoneNumber != null)
                contactViewHolder.txtViewPhoneNumber.setText(phoneNumber);
            else
                contactViewHolder.txtViewPhoneNumber.setText("Unknown");


// start async task to check if phone number is in a database

// if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
// if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK"); 



            new JSONParse().execute(phoneNumber);



            Uri uri = getPhotoUri(Long.parseLong(fetchContactIdFromPhoneNumber(phoneNumber)));

            if (uri != null) {
                contactViewHolder.imgContact.setImageURI(uri);
            } else {
                contactViewHolder.imgContact
                        .setImageResource(R.drawable.ic_launcher);
            }

        return convertView;
    }

    private String fetchContactIdFromPhoneNumber(String phoneNumber) {

        Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,Uri.encode(phoneNumber));
        Cursor cFetch = getContentResolver().query(uri,
                new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup._ID },
                null, null, null);

        String contactId = "";


        if (cFetch.moveToFirst()) {

            cFetch.moveToFirst();

                contactId = cFetch.getString(cFetch
                        .getColumnIndex(PhoneLookup._ID));

        }

        System.out.println(contactId);

        return contactId;       

    }


    public Uri getPhotoUri(long contactId) {
        ContentResolver contentResolver = getContentResolver();

        try {
            Cursor cursor = contentResolver
                    .query(ContactsContract.Data.CONTENT_URI,
                            null,
                            ContactsContract.Data.CONTACT_ID
                                    + "="
                                    + contactId
                                    + " AND "

                                    + ContactsContract.Data.MIMETYPE
                                    + "='"
                                    + ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE
                                    + "'", null, null);

            if (cursor != null) {
                if (!cursor.moveToFirst()) {
                    return null; // no photo
                }
            } else {
                return null; // error in cursor process
            }

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        Uri person = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, contactId);
        return Uri.withAppendedPath(person,
                ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
    }

    public class ContactViewHolder {
        ImageView imgContact;
        TextView txtViewContactName;
        TextView txtViewPhoneNumber;
        TextView txtViewCheck;
    }

}

private void readContacts() {

    cr = getContentResolver();
    cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
}


// async check if gcm
private class JSONParse extends AsyncTask<String, String, JSONObject> {

    @Override
      protected void onPreExecute() {
          super.onPreExecute();

    }
    @Override
    protected JSONObject doInBackground(String... args) {


// is this the correct way to get the phoneNumber send in the execute 
        String phoneNumber = args[0];

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("cel", phoneNumber));
        JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);

        return json;
    }

     @Override
       protected void onPostExecute(JSONObject json) {

       try {
         JSONObject android = json.getJSONObject(TAG_OS);
          String error = android.optString(TAG_ERROR);
          if(Integer.parseInt(error) == 0){
            // if the async task returns true contactViewHolder.txtViewPhoneCheck.setText("OK");
            // return true;
          }
          if(Integer.parseInt(error) == 1){
            // if the async task returns false contactViewHolder.txtViewPhoneCheck.setText("NOT OK");
            // return false;  
          }
      } catch (JSONException e) {
        e.printStackTrace();
      }

     }
  }

@Override
protected void onDestroy() {

    super.onDestroy();

    if (cur != null) {
        cur.close();
    }
}
}

感谢您的帮助。

你走在正确的轨道上:

new JSONParse().execute(phoneNumber);

只需确保 phoneNumber 是一个字符串。

is this the correct way to get the phoneNumber send in the execute

String phoneNumber = args[0];

是的,这是正确的方法。 AsyncTask 接受的第一个也是唯一一个参数是 phoneNumber 并且 String..args 的索引从 0

开始

现在,在您的 onPostExecute 方法中,我不熟悉 JSONObject class,但我认为如果:

if(Integer.parseInt(error) == 0)

if(Integer.parseInt(error) == 1){

return 是的,那么您可以继续根据需要设置编辑文本吗?