change ImageView Resource in a ListView Layout from an AsyncTask that load contactsList

◇◆丶佛笑我妖孽 提交于 2019-12-23 05:47:05

问题


i want to change (with a condition) an ImageView resource in a ListView Layout from My AsyncTask that load a contacts list and put it to the listview in FindPeopleFragment.java

how can i do it ?

sorry if my english is bad !!!!

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();
        }



    }


}

lv_layout.xml:

<?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>

the condition i want to do is related to the phone number from each contact in the listview it consiste to get the provider number and compare it with (getProvider()) and tell which is the provider of the number and put his puce image (from drawable) in the ImageView (iv_puce)

getProvider():

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;
        }

回答1:


You need to let the ListView know that your adapter's data has changed. Do the below in your onPostExecute method.

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

        // Add this line
        mAdapter.notifyDataSetChanged();

        dialog.dismiss();
    }

Good luck.



来源:https://stackoverflow.com/questions/23638470/change-imageview-resource-in-a-listview-layout-from-an-asynctask-that-load-conta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!