Android 从加载contactsList的异步任务更改ListView布局中的ImageView资源

Android 从加载contactsList的异步任务更改ListView布局中的ImageView资源,android,listview,android-listview,android-asynctask,imageview,Android,Listview,Android Listview,Android Asynctask,Imageview,我想从AsyncTask中更改ListView布局中的ImageView资源(带条件),该任务加载联系人列表并将其放入FindPeopleFragment.java中的ListView 我怎么做 对不起,如果我的英语不好 FindPeopleFragment.java: import java.io.File; import java.io.FileOutputStream; import android.app.Fragment; import android.app.ProgressDia

我想从AsyncTask中更改ListView布局中的ImageView资源(带条件),该任务加载联系人列表并将其放入FindPeopleFragment.java中的ListView

我怎么做

对不起,如果我的英语不好

FindPeopleFragment.java:

import java.io.File;
import java.io.FileOutputStream;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.SimpleCursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

public class FindPeopleFragment extends Fragment  {

public FindPeopleFragment(){}

    SimpleCursorAdapter mAdapter;
    MatrixCursor mMatrixCursor;



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {


        View rootView = inflater.inflate(R.layout.fragment_find_people, container, false);



     // The contacts from the contacts content provider is stored in this cursor
        mMatrixCursor = new MatrixCursor(new String[] { "_id","name","photo","details"} );

        // Adapter to set data in the listview
        mAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(),
            R.layout.lv_layout,
            null,
            new String[] { "name","photo","details"},
            new int[] { R.id.tv_name,R.id.iv_photo,R.id.tv_details}, 0);

        // Getting reference to listview
        ListView lstContacts = (ListView) rootView.findViewById(R.id.listview);

        // Setting the adapter to listview
        lstContacts.setAdapter(mAdapter);

        // Creating an AsyncTask object to retrieve and load listview with contacts
        ListViewContactsLoader listViewContactsLoader = new ListViewContactsLoader();

        // Starting the AsyncTask process to retrieve and load listview with contacts
        listViewContactsLoader.execute();




        return rootView;
    }

    /** An AsyncTask class to retrieve and load listview with contacts */
    private class ListViewContactsLoader extends AsyncTask<Void, Void, Cursor>{

        //A Progress dialog with a spinning wheel, to instruct the user about the app's current state
        ProgressDialog dialog = ProgressDialog.show(getActivity(), "Please Wait", "Retrieving Contacts...", true);

        @Override
        protected Cursor doInBackground(Void... params) {
            Uri contactsUri = ContactsContract.Contacts.CONTENT_URI;

            // Querying the table ContactsContract.Contacts to retrieve all the contacts
            Cursor contactsCursor = getActivity().getContentResolver().query(contactsUri, null, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " ASC ");

            if(contactsCursor.moveToFirst()){
                do{
                    long contactId = contactsCursor.getLong(contactsCursor.getColumnIndex("_ID"));

                    Uri dataUri = ContactsContract.Data.CONTENT_URI;

                    // Querying the table ContactsContract.Data to retrieve individual items like
                    // home phone, mobile phone, work email etc corresponding to each contact
                    Cursor dataCursor = getActivity().getContentResolver().query(dataUri, null,
                                        ContactsContract.Data.CONTACT_ID + "=" + contactId,
                                        null, null);

                    String displayName="";
                    String nickName="";
                    String homePhone="";
                    String mobilePhone="";
                    String workPhone="";
                    String otherPhone="";
                    String photoPath="" + R.drawable.blank;
                    byte[] photoByte=null;
                    String homeEmail="";
                    String workEmail="";
                    String companyName="";
                    String title="";

                    if(dataCursor.moveToFirst()){
                        // Getting Display Name
                        displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
                        do{

                            // Getting NickName
                            if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
                                nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));



                            // Getting Phone numbers
                            if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
                                switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_HOME :
                                        homePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE :
                                        mobilePhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_WORK :
                                        workPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;
                                    case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER :
                                        otherPhone = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;

                                }
                            }



                            // Getting EMails
                            if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {
                                switch(dataCursor.getInt(dataCursor.getColumnIndex("data2"))){
                                    case ContactsContract.CommonDataKinds.Email.TYPE_HOME :
                                        homeEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;
                                    case ContactsContract.CommonDataKinds.Email.TYPE_WORK :
                                        workEmail = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                        break;
                                }
                            }

                            // Getting Organization details
                            if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
                                companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
                                title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
                            }

                            // Getting Photo
                            if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){
                                photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));

                                if(photoByte != null) {
                                    Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);

                                    // Getting Caching directory
                                    File cacheDirectory = getActivity().getBaseContext().getCacheDir();

                                    // Temporary file to store the contact image
                                    File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+contactId+".png");

                                    // The FileOutputStream to the temporary file
                                    try {
                                        FileOutputStream fOutStream = new FileOutputStream(tmpFile);

                                        // Writing the bitmap to the temporary file as png file
                                        bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

                                        // Flush the FileOutputStream
                                        fOutStream.flush();

                                        //Close the FileOutputStream
                                        fOutStream.close();

                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                    photoPath = tmpFile.getPath();
                                }
                            }
                        }while(dataCursor.moveToNext());
                        String details = "";

                        // Concatenating various information to single string
                        if(homePhone != null && !homePhone.equals("") )
                            details = "HomePhone : " + homePhone + "\n";
                        if(mobilePhone != null && !mobilePhone.equals("") )
                            details += "MobilePhone : " + mobilePhone + "\n";
                        if(workPhone != null && !workPhone.equals("") )
                            details += "WorkPhone : " + workPhone + "\n";
                        if(otherPhone != null && !otherPhone.equals("") )
                            details += "OtherPhone : " + otherPhone + "\n";
                        if(nickName != null && !nickName.equals("") )
                            details += "NickName : " + nickName + "\n";
                        if(homeEmail != null && !homeEmail.equals("") )
                            details += "HomeEmail : " + homeEmail + "\n";
                        if(workEmail != null && !workEmail.equals("") )
                            details += "WorkEmail : " + workEmail + "\n";
                        if(companyName != null && !companyName.equals("") )
                            details += "CompanyName : " + companyName + "\n";
                        if(title != null && !title.equals("") )
                            details += "Title : " + title + "\n";

                        // Adding id, display name, path to photo and other details to cursor
                        mMatrixCursor.addRow(new Object[]{ Long.toString(contactId),displayName,photoPath,details});



                    }


                }while(contactsCursor.moveToNext());
            }
            return mMatrixCursor;
        }

        @Override
        protected void onPostExecute(Cursor result) {
            // Setting the cursor containing contacts to listview
            mAdapter.swapCursor(result);

            dialog.dismiss();
        }



    }


}
导入java.io.File;
导入java.io.FileOutputStream;
导入android.app.Fragment;
导入android.app.ProgressDialog;
导入android.database.Cursor;
导入android.database.MatrixCursor;
导入android.graphics.Bitmap;
导入android.graphics.BitmapFactory;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.provider.contacts合同;
导入android.support.v4.widget.SimpleCursorAdapter;
导入android.view.LayoutInflater;
导入android.view.view;
导入android.view.ViewGroup;
导入android.widget.ListView;
公共类FindPeopleFragment扩展了片段{
public FindPeopleFragment(){}
简单的适应;
MatrixCursor mMatrixCursor;
@凌驾
创建视图上的公共视图(布局、充气机、视图组容器、,
Bundle savedInstanceState){
视图根视图=充气机。充气(R.layout.fragment\u find\u people,container,false);
//联系人内容提供程序中的联系人存储在此光标中
mMatrixCursor=新矩阵xcursor(新字符串[]{“\u id”,“name”,“photo”,“details”});
//用于在listview中设置数据的适配器
mAdapter=new SimpleCursorAdapter(getActivity().getBaseContext(),
R.布局。lv_布局,
无效的
新字符串[]{“名称”、“照片”、“详细信息”},
新int[]{R.id.tv_name,R.id.iv_photo,R.id.tv_details},0);
//获取对listview的引用
ListView lstContacts=(ListView)rootView.findViewById(R.id.ListView);
//将适配器设置为listview
lstContacts.setAdapter(mAdapter);
//创建AsyncTask对象以检索和加载带有联系人的listview
ListViewContactsLoader ListViewContactsLoader=新建ListViewContactsLoader();
//启动AsyncTask进程以检索和加载带有联系人的listview
listViewContactsLoader.execute();
返回rootView;
}
/**用于检索和加载带有联系人的listview的AsyncTask类*/
私有类ListViewContactsLoader扩展异步任务{
//带有旋转滚轮的进度对话框,用于向用户指示应用程序的当前状态
ProgressDialog=ProgressDialog.show(getActivity(),“请稍候”,“正在检索联系人…”,true);
@凌驾
受保护的游标doInBackground(无效…参数){
Uri contactsUri=ContactsContract.Contacts.CONTENT\u Uri;
//查询ContactsContract.Contacts表以检索所有联系人
游标contactsCursor=getActivity().getContentResolver().query(contactsUri,null,null,
Contacts contract.Contacts.DISPLAY_NAME+“ASC”);
如果(contactsUrsor.moveToFirst()){
做{
long contactId=contactsCursor.getLong(contactsCursor.getColumnIndex(“\u ID”);
Uri dataUri=ContactsContract.Data.CONTENT\u Uri;
//查询ContactsContract.Data表以检索单个项目,如
//每个联系人对应的家庭电话、手机、工作电子邮件等
游标dataCursor=getActivity().getContentResolver().query(dataUri,null,
contacts contract.Data.CONTACT_ID+“=”+contactId,
空,空);
字符串displayName=“”;
字符串昵称=”;
字符串homePhone=“”;
字符串mobilePhone=“”;
字符串workPhone=“”;
字符串otherPhone=“”;
字符串photoPath=”“+R.drawable.blank;
字节[]photoByte=null;
字符串homemail=“”;
字符串workEmail=“”;
字符串companyName=“”;
字符串标题=”;
if(dataCursor.moveToFirst()){
//获取显示名称
displayName=dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME));
做{
//获得昵称
if(dataCursor.getString(dataCursor.getColumnIndex(“mimetype”)).equals(ContactsContract.CommonDataTypes.昵称.CONTENT\u ITEM\u TYPE))
昵称=dataCursor.getString(dataCursor.getColumnIndex(“data1”));
//获取电话号码
if(dataCursor.getString(dataCursor.getColumnIndex(“mimetype”)).equals(ContactsContract.CommonDataTypes.Phone.CONTENT\u ITEM\u TYPE)){
开关(dataCursor.getInt(dataCursor.getColumnIndex(“data2”)){
案例联系人contract.commondatatypes.Phone.TYPE\u HOME:
homePhone=dataCursor.getString(dataCursor.getColumnIndex(“data1”));
打破
案例联系人contract.commondatatypes.Phone.TYPE\u手机:
mobilePhone=dataCursor.getString(dataCursor.getColumnIndex(“data1”));
打破
案例联系人contract.commondatatypes.Phone.TYPE\u工作:
workPhone=dataCursor.getString(dataCursor.getColumnIndex(“data1”));
打破
案例联系人contract.commondatatypes.Phone.TYPE\u其他:
另外
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/iv_puce"
        android:layout_height="60dp"
        android:layout_width="60dp"
        android:padding="10dp"
        android:src="@drawable/none"
        />

    <ImageView
        android:id="@+id/iv_photo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="4dp"
            android:textSize="15sp" />

        <TextView
            android:id="@+id/tv_details"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="4dp"
            android:textSize="12sp" />

    </LinearLayout>

</LinearLayout>
String[] prefix = new String[]{"0610","0611","0613","0615","0616","0618","0622","0623",
                                        "0624","0628","0641","0642","0648","0650","0651","0652",
                                        "0653","0654","0655","0658","0659","0661","0662","0666",
                                        "0667","0668","0670","0671","0672","0673","0676","0677",
                                        "0678"," ","0612","0614","0617","0619","0620","0644","0645",
                                        "0649","0656","0657","0660","0663","0664","0665","0669","0674"
                                        ,"0675","0679"," ","0600","0601","0602","0603","0606","0626",
                                        "0627","0629","0630","0633","0634","0635","0638","0699"," ",
                                        "0640","0646","0647"," ","0526","0527","0540","0546","0547",
                                        "0533","0534","0550","0553"};

        String[] provider = new String[]{"iam","meditel","inwi","modem_inwi","bayn"};

        public String getProvider(String num){
            //0642212125
            //+212642848
            String ns;
            String msg = "";
            if(num.indexOf("+") != -1){
                ns = "0" +num.substring(4, 7);
            }else{
                ns = num.substring(0,4);
            }
            int j = 0;
            boolean found = false;
            for (int i = 0; i < prefix.length-1; i++) {
                if(prefix[i].equals(ns) & found == false){
                    msg = provider[j] ;
                    found = true;
                    if (msg == "inwi"){
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.inwi);
                    }
                    else if (msg == "meditel"){
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.meditel);
                    }
                    else if (msg == "bayn"){
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.bayn);
                    }
                    else if (msg == "iam"){
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.iam);
                    }
                    else if (msg == "modem_inwi"){
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.modem_inwi);
                    }
                    else{
                        ImageView Imgview = (ImageView) findViewById(R.id.imgViewOperator2);
                        Imgview.setImageResource(R.drawable.none);
                    }
                    //document.getElementById("src_img").innerHTML = "<img src='images/puces/" + provider[j] + ".png' alt='' />";
                    //              break;
                }
                else if(prefix[i] == " " & found == false){
                    j += 1;
                    //              msg = j + " " + ns + " " + provider[j];
                }
                else if(i == prefix.length & found == false){
                    msg = "";
                    //document.getElementById("src_img").innerHTML = "<img src='images/puces/none.png' alt='' />";
                }
            };
            return msg;
        }
 @Override
    protected void onPostExecute(Cursor result) {
        // Setting the cursor containing contacts to listview
        mAdapter.swapCursor(result);

        // Add this line
        mAdapter.notifyDataSetChanged();

        dialog.dismiss();
    }