- Create Project named ContactList.
 - Add following permission in android menifest file.
 
<uses-permission android:name="android.permission.READ_CONTACTS" />
- Add Following Code in MainActivity.java file
 
MainActivity.java
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
 MyCustomAdapter dataAdapter = null;
 Context context = this;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  new LongOperation().execute();
  checkButtonClick();
 }
 private class MyCustomAdapter extends ArrayAdapter<Phonebook> {
  private ArrayList<Phonebook> phonebookList;
  public MyCustomAdapter(Context context, int textViewResourceId,
  ArrayList<Phonebook> pbList) {
   super(context, textViewResourceId, pbList);
   this.phonebookList = new ArrayList<Phonebook>();
   this.phonebookList.addAll(pbList);
  }
  private class ViewHolder {
   TextView name, number;
   CheckBox selected;
   ImageView imgView;
  }
  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
   ViewHolder holder = null;
   Log.v("ConvertView", String.valueOf(position));
   if (convertView == null) {
    LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = vi.inflate(R.layout.blacklist_layout, null);
    holder = new ViewHolder();
    holder.name = (TextView) convertView.findViewById(R.id.tvName);
    holder.number = (TextView) convertView
      .findViewById(R.id.tvNumber);
    holder.selected = (CheckBox) convertView
      .findViewById(R.id.checkBox1);
    holder.imgView = (ImageView) convertView
      .findViewById(R.id.imgView);
    convertView.setTag(holder);
    holder.selected.setOnClickListener(new View.OnClickListener() {
     public void onClick(View v) {
      CheckBox cb = (CheckBox) v;
      Phonebook _state = (Phonebook) cb.getTag();
      _state.setChecked(cb.isChecked());
     }
    });
   } else {
    holder = (ViewHolder) convertView.getTag();
   }
   Phonebook state = phonebookList.get(position);
   holder.name.setText(state.getName());
   holder.number.setText(state.getNumber());
   holder.selected.setChecked(state.isChecked());
   Log.v("getImgUri", "" + state.getImgUri());
   holder.imgView.setImageURI(state.getImgUri());
   if (holder.imgView.getDrawable() == null) {
    holder.imgView.setImageResource(R.drawable.ic_launcher);
   }
   holder.selected.setTag(state);
   return convertView;
  }
 }
 private void checkButtonClick() {
  Button myButton = (Button) findViewById(R.id.findSelected);
  myButton.setOnClickListener(new OnClickListener() {
   @Override
   public void onClick(View v) {
    ArrayList<Phonebook> stateList = dataAdapter.phonebookList;
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < stateList.size(); i++) {
     Phonebook state = stateList.get(i);
     if (state.isChecked()) {
      //Get selected contact information
      //sb.append("\nImage URI:" + state.getImgUri().toString());
      sb.append("\nName:" + state.getName());
      sb.append("\nNumber:" + state.getNumber());
      sb.append("\n-----");
     }
    }
    Toast.makeText(context, ":" + sb.toString(), Toast.LENGTH_LONG)
      .show();
   }
  });
 }
 ProgressDialog mProgressDialog;
 Intent i;
 private class LongOperation extends AsyncTask<Void, Void, Void> {
  @Override
  protected Void doInBackground(Void... params) {
   runOnUiThread(new Runnable() {
    @Override
    public void run() {
     ArrayList<Phonebook> phonebookList = new ArrayList<Phonebook>();
     ContentResolver cr = getContentResolver();
     Cursor cur = cr.query(
       ContactsContract.Contacts.CONTENT_URI, null, null,
       null, null);
     if (cur.getCount() > 0) {
      while (cur.moveToNext()) {
       String id = cur
         .getString(cur
           .getColumnIndex(ContactsContract.Contacts._ID));
       String 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()) {
         String phone = pCur
           .getString(pCur
             .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
         Uri uri = Utils
           .getPhotoUri(
             Long.parseLong(Utils
               .fetchContactIdFromPhoneNumber(
                 phone,
                 context)),
             context);
         // ---------------------------------------------------------------------------
         Phonebook _states = new Phonebook(name,
           phone, false, uri);
         phonebookList.add(_states);
         // ---------------------------------------------------------------------------
        }
        pCur.close();
       }
      }
      // create an ArrayAdaptar from the String Array
      dataAdapter = new MyCustomAdapter(MainActivity.this,
        R.layout.blacklist_layout, phonebookList);
      ListView listView = (ListView) findViewById(R.id.listView1);
      // Assign adapter to ListView
      listView.setAdapter(dataAdapter);
      listView.setOnItemClickListener(new OnItemClickListener() {
       public void onItemClick(AdapterView<?> parent,
         View view, int position, long id) {
       }
      });
     }
    }
   });
   return null;
  }
  @Override
  protected void onPostExecute(Void result) {
   if (mProgressDialog.isShowing()) {
    mProgressDialog.dismiss();
   }
  }
  @Override
  protected void onPreExecute() {
   ShowLoading();
  }
  @Override
  protected void onProgressUpdate(Void... values) {
  }
 }
 private void ShowLoading() {
  mProgressDialog = new ProgressDialog(this);
  mProgressDialog.setMessage("Loading Contacts ....");
  mProgressDialog.setIndeterminate(false);
  mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
  mProgressDialog.setCancelable(false);
  mProgressDialog.show();
 }
}
- Add XML code in layout file, activity_main.xml
 
activity_main.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="#fff"
    android:gravity="center"
    android:orientation="vertical" >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#000"
        android:gravity="center"
        android:orientation="horizontal" >
        <TextView
            style="@style/titlebar_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:textSize="18dp"
            android:text="Contacts" />
        <Button
            android:id="@+id/findSelected"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Save"
            android:textColor="#ffffff" />
    </LinearLayout>
    <ListView
        android:id="@+id/listView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:divider="#BC0061"
        android:dividerHeight="2dp"
        android:background="@android:color/transparent"
        android:cacheColorHint="@android:color/transparent"
        android:padding="10dp" />
</LinearLayout>
After Added above code you will get error in some code but don't worry.Go to step 2 and add remaining code.
this is good!
ReplyDeletetone
good content
ReplyDeletekredit tanpa angunan