<?xml version="1.0"
encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/white" >
    <RelativeLayout
       
android:id="@+id/relativeLayout1"
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content"
       
android:layout_alignParentLeft="true"
       
android:layout_alignParentTop="true"
       
android:background="@android:color/darker_gray"
>
        <TextView
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:layout_centerHorizontal="true"
           
android:layout_centerVertical="true"
           
android:text="ContactList"
           
android:textAppearance="?android:attr/textAppearanceLarge"
/>
        <Button
           
android:id="@+id/cnt_btn_Refresh"
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:layout_alignParentRight="true"
           
android:layout_centerVertical="true"
           
android:layout_marginRight="10dp"
           
android:text="Refresh" />
    </RelativeLayout>
    <!-- Center Part -->
    <LinearLayout
       
android:id="@+id/center"
       
android:layout_width="fill_parent"
       
android:layout_height="fill_parent"
       
android:layout_below="@+id/relativeLayout1"
       
android:orientation="vertical"
>
        <EditText
           
android:id="@+id/cnt_edt_search"
           
android:layout_width="fill_parent"
           
android:layout_height="wrap_content"
           
android:layout_marginBottom="5dp"
           
android:layout_marginTop="5dp"
           
android:background="@drawable/bg_search"
           
android:drawableLeft="@drawable/search_icon"
           
android:drawablePadding="10dp"
           
android:gravity="center_vertical"
           
android:hint="Search"
           
android:paddingLeft="10dp"
           
android:paddingRight="10dp"
           
android:singleLine="true"
           
android:textSize="15sp"
>
        </EditText>
        <TextView
           
android:layout_width="fill_parent"
           
android:layout_height="1dp"
           
android:background="@android:color/darker_gray"
/>
        <LinearLayout
           
android:layout_width="fill_parent"
           
android:layout_height="0dp"
           
android:layout_weight="1"
           
android:orientation="vertical"
>
            <ListView
                android:id="@+id/allcontacts_list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:cacheColorHint="#00000000"
                android:divider="@null"
                android:smoothScrollbar="true"
                android:textFilterEnabled="true"
>
            </ListView>
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>
lyt_contectlist.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:background="@android:color/white"
    android:orientation="vertical" >
    <LinearLayout
       
android:layout_width="fill_parent"
       
android:layout_height="wrap_content"
       
android:background="@drawable/list"
       
android:gravity="center_vertical"
       
android:orientation="horizontal"
       
android:paddingLeft="10dp"
       
android:paddingRight="10dp"
       
android:weightSum="1"
>
        <TextView
           
android:id="@+id/txtDisplayName"
           
android:layout_width="0dp"
           
android:layout_height="wrap_content"
           
android:layout_weight="1"
            android:text="Contact_name"
           
android:textColor="@android:color/black"
           
android:textSize="17sp"
           
android:textStyle="bold"
>
        </TextView>
        <Button
           
android:id="@+id/btn_arrow"
           
android:layout_width="wrap_content"
           
android:layout_height="wrap_content"
           
android:background="@drawable/arrow"
>
        </Button>
    </LinearLayout>
    <TextView
       
android:layout_width="fill_parent"
       
android:layout_height="1dp"
       
android:background="@android:color/darker_gray"
/>
</LinearLayout>
Class Contact:
public class Contact
{
      public String Contact_Id;
      public String Contact_DisplayName;
      public String Contact_MobNumber;
      public String Contact_email;  
}
MainActivity:
import
java.util.ArrayList;
import java.util.List;
import
android.app.Activity;
import
android.app.ProgressDialog;
import
android.content.ContentResolver;
import
android.content.Context;
import
android.database.Cursor;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.provider.ContactsContract;
import
android.provider.ContactsContract.CommonDataKinds.Phone;
import
android.text.Editable;
import
android.text.TextWatcher;
import
android.util.Log;
import
android.view.LayoutInflater;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.view.ViewGroup;
import
android.view.WindowManager;
import
android.widget.ArrayAdapter;
import
android.widget.Button;
import
android.widget.EditText;
import android.widget.Filter;
import
android.widget.Filterable;
import
android.widget.ListView;
import
android.widget.TextView;
import
android.widget.Toast;
public class MainActivity extends Activity 
{
      private ProgressDialog dialog;      
      private EditText Edt_Search;
      private ListView listview;
      private
ArrayList<Contact>arrlist_contact;
      private ContactAdapter itemAdaptor; 
      int textlength=0; 
      String
cnt_name= "";
      String
phoneNumber= "";
      String
emailAddress ="";
      String
name="";
      String
mobile="";
      String
email="";
      Button
btn_Refresh;
      @Override
      protected void onCreate(Bundle
savedInstanceState) 
      {
            // TODO
Auto-generated method stub
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            Initialize_Controls();
            new
GetAllcontacts().execute();
            Search_Contects();      
            btn_Refresh.setOnClickListener(new
OnClickListener() 
            {
                  @Override
                  public void onClick(View
arg0) 
                  {
                        arrlist_contact=new
ArrayList<Contact>();
                        new
GetAllcontacts().execute();                 
                  }
            });
      }
      private void
Initialize_Controls() 
      {
            Edt_Search=(EditText)
findViewById(R.id.cnt_edt_search);
            listview=(ListView)
findViewById(R.id.allcontacts_list);    
            btn_Refresh=(Button)
findViewById(R.id.cnt_btn_Refresh);
      }           
      public class GetAllcontacts extends
AsyncTask<Void, Void, Void> 
      {
            @Override
            protected void onPreExecute() 
            {
                  dialog = new
ProgressDialog(MainActivity.this);       
                  dialog.setMessage("Loading
Contacts...");
                  dialog.setCancelable(false);
                  dialog.show();
                  super.onPreExecute();
            }
            @Override
            protected Void
doInBackground(Void... params) 
            {
                  readContacts();         
                  return null;
            }
            @Override
            protected void
onPostExecute(Void result) 
            {
                  super.onPostExecute(result);
                  if(dialog.isShowing()&&
dialog!=null)
                  {
                        dialog.dismiss();
                  }
                  if(arrlist_contact.size()>0)
                  {                 
                        itemAdaptor = new ContactAdapter(arrlist_contact,MainActivity.this);                  
                        listview.setAdapter(itemAdaptor);                     
                  }     
            }
      }
      public void readContacts()
      {           
            Cursor
cur =null;
            try 
            {
                  arrlist_contact=new
ArrayList<Contact>();
                  ContentResolver
cr = getContentResolver();
                  cur=
cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null,Phone.DISPLAY_NAME + "
ASC");
                  Log.i("Total
Contacts==",""+cur.getCount());
                  if (cur.getCount()
> 0) 
                  {
                        btn_Refresh.setVisibility(View.VISIBLE);
                        while
(cur.moveToNext()) 
                        {
                              Contact
c =new Contact();
                              String
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
                              cnt_name =
cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME ));
                              if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
                              {                             
                                    // get the
phone number
                                    Cursor
pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" =
?",new String[]{id}, null);
                                    while
(pCur.moveToNext()) 
                                    {
                                          phoneNumber =
pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));                               
                                    }
                                    pCur.close();
                                    // get email
and type
                                    Cursor
emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,null,ContactsContract.CommonDataKinds.Email.CONTACT_ID + " =
?",new String[]{id}, null);
                                    while
(emailCur.moveToNext()) 
                                    {
                                          emailAddress =
emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));                                                                   
                                    }
                                    emailCur.close();                  
                                    c.Contact_Id=id;
                                    c.Contact_DisplayName=cnt_name;
                                    c.Contact_MobNumber=phoneNumber;
                                    c.Contact_email=emailAddress;
                                    arrlist_contact.add(c);
                              }
                        }
                  }
                  else
                  {           
                        btn_Refresh.setVisibility(View.VISIBLE);
                        Toast.makeText(MainActivity.this,"No
contact available in Contact list",Toast.LENGTH_LONG).show();
                  }
            }
            catch (Exception e) 
            {
                  btn_Refresh.setVisibility(View.VISIBLE);
                  Toast.makeText(MainActivity.this,"No
contact available in Contact list",Toast.LENGTH_LONG).show();
                  e.printStackTrace();
            }
            finally
            {
                  cur.close();
            }
      }
 //Search Method:
      private void
Search_Contects() 
      {
            Edt_Search.addTextChangedListener(new TextWatcher()
            {
                  public void
afterTextChanged(Editable s)
                  {
                        // Abstract
Method of TextWatcher Interface.
                  }
                  public void
beforeTextChanged(CharSequence s,
                              int start, int count, int after)
                  {
                        // Abstract
Method of TextWatcher Interface.
                  }
                  public void
onTextChanged(CharSequence s,int start, int before, int count)
                  {
                        try 
                        {
                              System.out.println("Text
["+s+"] - Start ["+start+"] - Before ["+before+"] -
Count ["+count+"]");
                              if(s.length()>0)
                              {
                                    if (count <
before) 
                                    {
                                          // We're
deleting char so we need to reset the adapter data
                                          itemAdaptor.resetData();
                                    }
                                    itemAdaptor.getFilter().filter(s.toString());
                              }
                              else
                              {                                   
                                    itemAdaptor.resetData();                              
                              }
                        }
                        catch (Exception e) 
                        {
                              e.printStackTrace();
                        }
                  }
            });
      }
//ContactAdapter
And Filter
      public class ContactAdapter extends
ArrayAdapter<Contact> implements Filterable 
      {
            private
List<Contact> CntList;
            Context
context;
            private Filter ContactFilter;
            private
List<Contact> OrgContactList;
            public
ContactAdapter(List<Contact> cntList, Context ctx) 
            {
                  super(ctx, R.layout.lyt_contactlist, cntList);
                  this.CntList = cntList;
                  this.context = ctx;
                  this.OrgContactList = cntList;
            }
            public int getCount() {
                  return CntList.size();
            }
            public Contact
getItem(int position) {
                  return CntList.get(position);
            }
            public long getItemId(int position) 
            {
                  return CntList.get(position).hashCode();
            }
            public View getView(int position, View
convertView, ViewGroup parent) 
            {           
                  View
view = convertView;                  
                  try 
                  {
                        Contact
c=CntList.get(position);                      
                        String
name_set=c.Contact_DisplayName;                      
                        LayoutInflater
lyt_Inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);    
                        view
= lyt_Inflater.inflate(R.layout.lyt_contactlist, null);
                        TextView
txt_name = (TextView) view.findViewById(R.id.txtDisplayName);
                        txt_name.setText(name_set);
                        view.setTag(c);
                        view.setOnClickListener(new
OnClickListener() 
                        {     
                              @Override
                              public void onClick(View v)
                              {
                                    Contact
temp1 =  (Contact) v.getTag();
                                    name= temp1.Contact_DisplayName;
                                    mobile = temp1.Contact_MobNumber;
                                    email = temp1.Contact_email;
                                    Toast.makeText(MainActivity.this,"Name:"+name+" "+"Number:"+mobile+" "+"Email:"+email,Toast.LENGTH_LONG).show();
                              }
                        });
                  }
                  catch (Exception e) 
                  {
                        System.out.println(e.toString());
                  }
                  return view;
            }
            public void resetData() 
            {
                  CntList = OrgContactList;
            }     
            @Override
            public Filter
getFilter() 
            {
                  if (ContactFilter == null)
                        ContactFilter = new
ContactFilter();
                  return ContactFilter;
            }
            private class ContactFilter extends Filter 
            {           
                  @Override
                  protected FilterResults
performFiltering(CharSequence constraint) 
                  {
                        FilterResults
results = new FilterResults();
                        // We
implement here the filter logic
                        if (constraint == null ||
constraint.length() == 0) 
                        {
                              // No filter
implemented we return all the list
                              results.values = OrgContactList;
                              results.count = OrgContactList.size();
                        }
                        else 
                        {
                              // We perform
filtering operation
                              ArrayList<Contact>
nPlanetList = new ArrayList<Contact>();
                              for (Contact p : CntList) 
                              {
                                    if (p.Contact_DisplayName.toUpperCase().startsWith(constraint.toString().toUpperCase()))
                                          nPlanetList.add(p);
                              }
                              results.values = nPlanetList;
                              results.count =
nPlanetList.size();
                        }
                        return results;
                  }
                  @SuppressWarnings("unchecked")
                  @Override
                  protected void
publishResults(CharSequence constraint,
                              FilterResults
results) 
                  {
                        // Now we have
to inform the adapter about the new list filtered
                        if (results.count == 0)
                              notifyDataSetInvalidated();
                        else 
                        {
                              CntList =
(ArrayList<Contact>) results.values;
                              notifyDataSetChanged();
                        }
                  }
            }
      }     
}
Permission:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Download full source code from here : ContactListSearch
RefLink:
http://www.thaicreate.com/mobile/android-contact-list.html
http://techiedreams.com/custom-contacts-picker-with-images-filtering-indexed-scrolling/
Download full source code from here : ContactListSearch
RefLink:
http://www.thaicreate.com/mobile/android-contact-list.html
http://techiedreams.com/custom-contacts-picker-with-images-filtering-indexed-scrolling/
I
will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank
you :)

 
 
No comments:
Post a Comment