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



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

到目前为止,我创建了一个带有自定义适配器的listview,可以显示联系人姓名、号码和图像。我添加了第四个字段,它应该显示电话号码是否在数据库中。

我使用asynctask来获取这样的json {"android":{"error":"0"}},如果数字在数据库中,则为{"android":{"error":"1"}}。

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

我在一个类中使用的所有代码。

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是一个字符串。

这是在执行

中获取phoneNumber发送的正确方法吗?
String phoneNumber = args[0];

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

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

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

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

返回true,那么您可以继续设置所需的edittext ?

相关内容

  • 没有找到相关文章

最新更新