【问题标题】:change ImageView Resource in a ListView Layout from an AsyncTask that load contactsList从加载联系人列表的 AsyncTask 更改 ListView 布局中的 ImageView 资源
【发布时间】:2014-05-13 18:02:02
【问题描述】:

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

我该怎么做?

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

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>

我想要做的条件与列表视图中每个联系人的电话号码有关 它包括获取提供者编号并将其与 (getProvider()) 进行比较并判断哪个是该编号的提供者 并将他的 puce 图像(来自 drawable)放入 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;
        }

【问题讨论】:

  • 请大家帮忙

标签: android listview android-listview android-asynctask imageview


【解决方案1】:

您需要让 ListView 知道您的适配器的数据已更改。在您的 onPostExecute 方法中执行以下操作。

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

        // Add this line
        mAdapter.notifyDataSetChanged();

        dialog.dismiss();
    }

祝你好运。

【讨论】:

  • 你能解释一下吗!!
  • 在答案中检查我上面的编辑。我无法粘贴代码。
  • 感觉你还没明白我要做什么
  • 对不起,如果我不能完全了解发生了什么。我的理解是,当您的 AsyncTask 完成时,您希望使用结果更新 ListView。您已经在这样做了,只是您没有通知 ListView 更改。如果你认为这不是问题,你能告诉你到底注意到了什么吗?您是否看到带有 AsyncTask 结果的 ListView?或者,如果缺少其他一些行为,那么缺少的部分到底是什么,应该发生什么?
  • 感谢您努力帮助我,是的,我看到了 ListView 的结果,这很好,我想要的是我在 listview 布局中添加了一个 imageview,我希望它显示图像告诉每个联系人的号码提供者是什么,例如(verizon 或 t&t 或 sprint)在我的国家是(inwi、iam、meditel .....等)图像视图是 iv_puce 和“条件”来告诉哪个provider 一个数字是,是getProvider()
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2012-07-04
  • 2016-10-08
相关资源
最近更新 更多