0

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;
        }
JannahPro
  • 183
  • 6

1 Answers1

0

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.

Raghu
  • 351
  • 1
  • 4
  • can you explain more please !! – JannahPro May 13 '14 at 22:14
  • Check my edit above in the answer. I am not able to paste the code. – Raghu May 14 '14 at 06:03
  • i feel that you have not understand what i want to do – JannahPro May 15 '14 at 17:28
  • Sorry if I am not able to completely get what is going on. What I understand is that when your AsyncTask finishes, you want to update the ListView with the results. You are already doing that except that you are missing notifying the ListView the changes. If you think this is not the problem, can you please tell what exactly are you noticing? Are you seeing the ListView with the results from AsyncTask? Or if it is some other behavior that is missing, what exactly is the missing part and what should happen? – Raghu May 15 '14 at 18:55
  • thanks for your effort for trying to help me yes i'm seeing the ListView with the results and it's fine, what i want is i added an imageview to the listview layout and i want it to show an image to tell what is the provider of the number for each contacts like (verizon or t&t or sprint) in my country are (inwi, iam, meditel .....etc) the imageview is iv_puce and "the condition" to tell which provider a number is, is getProvider() – JannahPro May 17 '14 at 00:58
  • and i'm asking how to do it – JannahPro May 17 '14 at 15:16
  • guys i need help please – JannahPro May 20 '14 at 02:01
  • Sorry you are still having issue with this. One thing I noticed was that you are doing findViewById(R.id.imgViewOperator2). Shouldn't it be findViewById(R.id.iv_puce)? If this does not help, you may want to write your own Adapter extending the BaseAdapter and implementing getView. I hope someone else can see what you and I are missing and can help you with a better solution. – Raghu May 26 '14 at 07:13
  • but how can i reference iv_puce from lv_layout.xml in (FindPeopleFragment.java which inflate fragment_find_people.xml) i think thats my problem – JannahPro May 27 '14 at 16:20
  • I think you should override SimpleCursorAdaptor with your own adaptor and override the getView method. Call the super.getView() to do the most of the rendering by SimpleCursorAdaptor. After that, you set the iv_puce image to whatever the image using the logic that you already have. Check this link for a custom adapter (http://www.mysamplecode.com/2013/03/android-simplecursoradapter-alternate-row-color.html). Other option is to define a pseudo column and use the setViewBinder as explained in http://stackoverflow.com/questions/4776936/modifying-simplecursoradapters-data. Hope this helps. – Raghu May 28 '14 at 09:16
  • thank you so much for your support thru this post, your last comment doesn't help but i finally managed to get it to work. – JannahPro May 28 '14 at 12:44