Showing posts with label Android. Show all posts
Showing posts with label Android. Show all posts

Monday, September 11, 2017

Date Formatting / Date Conversion in Java / Android

Date Formatting is frequently used in programming and it is like headache for developers to format date to store into database and to display for users. Sometimes, app is crashed due to wrong date formatting. Here, I have give you best example of some different Date formats and get different Date Range.

First of all, Make new Java Class, name it Utils.java and copy below code into it.
DB_DATE_FORMAT and DISPLAY_DATE_FORMAT are different date formats and we can convert date from one format to another. You can use your own date format as well. To do this you just need to change 2 strings of date formats.

1. Display Date Format(): This method is convert date from DB_DATE_FORMAT to DISPLAY_DATE_FORMAT. Make sure your input in dtOldFormat is exact same as DB_DATE_FORMAT. Otherwise, it will throw an exception.

2. getLast7Days(): It will give you last 7 days list including todays date. Pair<String,String> function stores first and last date of range.

3. getPreviousMonth(): same as above, it will return Previous month's first and last date.

4. getSameMonthLastYear(): As name suggested it will give you same month date for previous month.

5. getCurrentMonthDateRange(): will give you current month date range

Other Private methods are used to set current calendar date and time for use of this class only.


public class Utils {

    public String DB_DATE_FORMAT = "yyyy-MM-dd";
    public String DISPLAY_DATE_FORMAT = "dd MMM yyyy";
    
    public String displayDateFormat(String dtOldFormat) {
        try {
            DateFormat inputFormat = new SimpleDateFormat(DB_DATE_FORMAT);
            DateFormat outputFormat = new SimpleDateFormat(DISPLAY_DATE_FORMAT);
            Date date = inputFormat.parse(dtOldFormat);
            String outputDateStr = outputFormat.format(date);
            return outputDateStr;
        } catch (Exception e) {
            e.printStackTrace();
            return dtOldFormat;
        }
    }

    public Pair<String,String> getLast7Days(){
        String begining,ending;
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DB_DATE_FORMAT);
        ending = sdf.format(cal.getTime());
        cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
        cal.add(Calendar.DAY_OF_WEEK, -6);
        begining = sdf.format(cal.getTime());
        return Pair.create(begining,ending);
    }

    public Pair<String, String> getPreviousMonth(){
        Date begining, end;

        Calendar calendar = GregorianCalendar.getInstance();
        calendar.add(Calendar.MONTH,-1);
        {
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            setTimeToBeginningOfDay(calendar);
            begining = calendar.getTime();
        }

        {
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            setTimeToEndofDay(calendar);
            end = calendar.getTime();
        }

        DateFormat inputFormat = new SimpleDateFormat(DB_DATE_FORMAT);
        return android.util.Pair.create(inputFormat.format(begining),inputFormat.format(end));
    }

    public Pair<String, String> getSameMonthLastYear(){
        Date begining, end;

        Calendar calendar = GregorianCalendar.getInstance();
        calendar.add(Calendar.YEAR,-1);
        {
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            setTimeToBeginningOfDay(calendar);
            begining = calendar.getTime();
        }

        {
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            setTimeToEndofDay(calendar);
            end = calendar.getTime();
        }

        DateFormat inputFormat = new SimpleDateFormat(DB_DATE_FORMAT);
        return android.util.Pair.create(inputFormat.format(begining),inputFormat.format(end));
    }
    public android.util.Pair<String, String> getCurrentMonthDateRange() {
        Date begining, end;

        {
            Calendar calendar = getCalendarForNow();
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
            setTimeToBeginningOfDay(calendar);
            begining = calendar.getTime();
        }

        {
            Calendar calendar = getCalendarForNow();
            calendar.set(Calendar.DAY_OF_MONTH,
                    calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
            setTimeToEndofDay(calendar);
            end = calendar.getTime();
        }

        DateFormat inputFormat = new SimpleDateFormat(DB_DATE_FORMAT);
        return android.util.Pair.create(inputFormat.format(begining),inputFormat.format(end));

    }
    private static Calendar getCalendarForNow() {
        Calendar calendar = GregorianCalendar.getInstance();
        calendar.setTime(new Date());
        return calendar;
    }

    private static void setTimeToBeginningOfDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
    }

    private static void setTimeToEndofDay(Calendar calendar) {
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
    }
}

Monday, November 16, 2015

Words- Characters Counter Android Demo



Description:

It is very easy to handle words and characters counter for your application. If you are developing an app which uses EditText, It is very important to give feature like word counter / Character counter within the app. Here is the full demo code which helps you.

First add below code to your activity_main.xml file.


activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_weight="0.4"
    android:orientation="vertical"
    android:paddingLeft="5dip"
    android:paddingRight="5dip" >

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingTop="10dp"
        android:paddingBottom="10dp" >

        <TextView
            android:id="@+id/tvCharWatcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerInParent="true"
            android:textSize="22dp"
            android:text="Characters:" />

        <TextView
            android:id="@+id/tvWordWatcher"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerInParent="true"
            android:textSize="22dp"
            android:text="Words:" />
    </RelativeLayout>

    <EditText
        android:id="@+id/note"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:autoText="false"
        android:background="@android:color/white"
        android:capitalize="none"
        android:ems="10"
        android:fadingEdge="none"
        android:gravity="top"
        android:scrollbars="vertical|horizontal"
        android:textColor="@android:color/black"
        android:textSize="22dp" >

        <requestFocus />
    </EditText>

</LinearLayout>


Your layout is ready, now you need to register components to MainActivity.java file and add below code step by step:

1. Create method init() to initialize needful variables,components etc.
2. TextWatcher class handles your EditText and it will call with every text you add.
3. WordCount() custom method counts words and return number of words.

Here, is the full code of MainActivity.java file

MainActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

EditText etText;
TextView tvWordWatcher, tvCharWatcher;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

init();
}

private void init() {

etText = (EditText) findViewById(R.id.note);
etText.setVerticalScrollBarEnabled(true);
etText.requestFocus();

tvCharWatcher = (TextView) findViewById(R.id.tvCharWatcher);
tvWordWatcher = (TextView) findViewById(R.id.tvWordWatcher);
tvCharWatcher.setText("Characters:0");
tvWordWatcher.setText("Words:0");

etText.addTextChangedListener(textWatcher);
}

TextWatcher textWatcher = new TextWatcher() {

@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
tvCharWatcher.setText("Characters:"
+ String.valueOf(s.length()));
tvWordWatcher.setText("Words:" + wordcount(s.toString()));
}

@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {

}

@Override
public void afterTextChanged(Editable s) {

}
};

public static long wordcount(String line) {
long numWords = 0;
int index = 0;
boolean prevWhiteSpace = true;
while (index < line.length()) {
char c = line.charAt(index++);
boolean currWhiteSpace = Character.isWhitespace(c);
if (prevWhiteSpace && !currWhiteSpace) {
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
}


Download Full Source Code: GitHub


Friday, September 5, 2014

3 Level Expandable ListView in android


Download Source Code


Source Code


MainActivity.java


import java.util.ArrayList;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.dow.lvlexplist.Product.SubCategory;
import com.dow.lvlexplist.Product.SubCategory.ItemList;
public class MainActivity extends ActionBarActivity {
private ArrayList<Product>pProductArrayList;
private ArrayList<SubCategory>pSubItemArrayList1,pSubItemArrayList2;
//private ArrayList<SubCategory>pSubItemArrayList2;
private LinearLayout mLinearListView;
boolean isFirstViewClick=false;
boolean isSecondViewClick=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLinearListView = (LinearLayout) findViewById(R.id.linear_listview);
ArrayList<ItemList> mItemListArray=new ArrayList<ItemList>();
mItemListArray.add(new ItemList("State 1", "20"));
mItemListArray.add(new ItemList("State 2", "50"));
mItemListArray.add(new ItemList("State 3", "20"));
mItemListArray.add(new ItemList("State 4", "50"));
ArrayList<ItemList> mItemListArray2=new ArrayList<ItemList>();
mItemListArray2.add(new ItemList("Price 1", "$500"));
mItemListArray2.add(new ItemList("Price 2", "$400"));
mItemListArray2.add(new ItemList("Price 3", "$200"));
mItemListArray2.add(new ItemList("Price 4", "$100"));
pSubItemArrayList1=new ArrayList<SubCategory>();
pSubItemArrayList1.add(new SubCategory("India", mItemListArray));
pSubItemArrayList1.add(new SubCategory("US", mItemListArray));
pSubItemArrayList1.add(new SubCategory("London", mItemListArray));
pSubItemArrayList2=new ArrayList<SubCategory>();
pSubItemArrayList2.add(new SubCategory("Android", mItemListArray2));
pSubItemArrayList2.add(new SubCategory("Apple", mItemListArray2));
pSubItemArrayList2.add(new SubCategory("Windows", mItemListArray2));
pProductArrayList=new ArrayList<Product>();
pProductArrayList.add(new Product("Country", pSubItemArrayList1));
pProductArrayList.add(new Product("Mobile", pSubItemArrayList2));
//pProductArrayList.add(new Product("Garments", pSubItemArrayList2));
/***
* adding item into listview
*/
for (int i = 0; i < pProductArrayList.size(); i++) {
LayoutInflater inflater = null;
inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView = inflater.inflate(R.layout.row_first, null);
final TextView mProductName = (TextView) mLinearView.findViewById(R.id.textViewName);
final RelativeLayout mLinearFirstArrow=(RelativeLayout)mLinearView.findViewById(R.id.linearFirst);
final ImageView mImageArrowFirst=(ImageView)mLinearView.findViewById(R.id.imageFirstArrow);
final LinearLayout mLinearScrollSecond=(LinearLayout)mLinearView.findViewById(R.id.linear_scroll);
if(isFirstViewClick==false){
mLinearScrollSecond.setVisibility(View.GONE);
mImageArrowFirst.setBackgroundResource(R.drawable.arw_lt);
}
else{
mLinearScrollSecond.setVisibility(View.VISIBLE);
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
}
mLinearFirstArrow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(isFirstViewClick==false){
isFirstViewClick=true;
mImageArrowFirst.setBackgroundResource(R.drawable.arw_down);
mLinearScrollSecond.setVisibility(View.VISIBLE);
}else{
isFirstViewClick=false;
mImageArrowFirst.setBackgroundResource(R.drawable.arw_lt);
mLinearScrollSecond.setVisibility(View.GONE); }
return false;
}
});
final String name = pProductArrayList.get(i).getpName();
mProductName.setText(name);
 
/**
*
*/
   for (int j = 0; j < pProductArrayList.get(i).getmSubCategoryList().size(); j++) {
LayoutInflater inflater2 = null;
inflater2 = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView2 = inflater2.inflate(R.layout.row_second, null);
 
TextView mSubItemName = (TextView) mLinearView2.findViewById(R.id.textViewTitle);
final RelativeLayout mLinearSecondArrow=(RelativeLayout)mLinearView2.findViewById(R.id.linearSecond);
final ImageView mImageArrowSecond=(ImageView)mLinearView2.findViewById(R.id.imageSecondArrow);
final LinearLayout mLinearScrollThird=(LinearLayout)mLinearView2.findViewById(R.id.linear_scroll_third);
if(isSecondViewClick==false){
mLinearScrollThird.setVisibility(View.GONE);
mImageArrowSecond.setBackgroundResource(R.drawable.arw_lt);
}
else{
mLinearScrollThird.setVisibility(View.VISIBLE);
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
}
mLinearSecondArrow.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(isSecondViewClick==false){
isSecondViewClick=true;
mImageArrowSecond.setBackgroundResource(R.drawable.arw_down);
mLinearScrollThird.setVisibility(View.VISIBLE);
}else{
isSecondViewClick=false;
mImageArrowSecond.setBackgroundResource(R.drawable.arw_lt);
mLinearScrollThird.setVisibility(View.GONE); }
return false;
}
});
final String catName = pProductArrayList.get(i).getmSubCategoryList().get(j).getpSubCatName();
mSubItemName.setText(catName);
/**
*
*/
 for (int k = 0; k < pProductArrayList.get(i).getmSubCategoryList().get(j).getmItemListArray().size(); k++) {
LayoutInflater inflater3 = null;
inflater3 = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View mLinearView3 = inflater3.inflate(R.layout.row_third, null);
 
TextView mItemName = (TextView) mLinearView3.findViewById(R.id.textViewItemName);
TextView mItemPrice = (TextView) mLinearView3.findViewById(R.id.textViewItemPrice);
final String itemName = pProductArrayList.get(i).getmSubCategoryList().get(j).getmItemListArray().get(k).getItemName();
final String itemPrice = pProductArrayList.get(i).getmSubCategoryList().get(j).getmItemListArray().get(k).getItemPrice();
mItemName.setText(itemName);
mItemPrice.setText(itemPrice);
mLinearView3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"Name:"+itemName+"\nID:"+itemPrice,Toast.LENGTH_LONG).show();
}
});
mLinearScrollThird.addView(mLinearView3);
 }
mLinearScrollSecond.addView(mLinearView2);
 
   }
 
   mLinearListView.addView(mLinearView);
} }
}

Product.java


import java.util.ArrayList;

public class Product {

private String pName;

private ArrayList<SubCategory> mSubCategoryList;

public Product(String pName, ArrayList<SubCategory> mSubCategoryList) {
super();
this.pName = pName;
this.mSubCategoryList = mSubCategoryList;
}

public String getpName() {
return pName;
}

public void setpName(String pName) {
this.pName = pName;
}

public ArrayList<SubCategory> getmSubCategoryList() {
return mSubCategoryList;
}

public void setmSubCategoryList(ArrayList<SubCategory> mSubCategoryList) {
this.mSubCategoryList = mSubCategoryList;
}

public static class SubCategory {

private String pSubCatName;
private ArrayList<ItemList> mItemListArray;

public SubCategory(String pSubCatName,
ArrayList<ItemList> mItemListArray) {
super();
this.pSubCatName = pSubCatName;
this.mItemListArray = mItemListArray;
}

public String getpSubCatName() {
return pSubCatName;
}

public void setpSubCatName(String pSubCatName) {
this.pSubCatName = pSubCatName;
}

public ArrayList<ItemList> getmItemListArray() {
return mItemListArray;
}

public void setmItemListArray(ArrayList<ItemList> mItemListArray) {
this.mItemListArray = mItemListArray;
}

public static class ItemList {

private String itemName;
private String itemPrice;

public ItemList(String itemName, String itemPrice) {
super();
this.itemName = itemName;
this.itemPrice = itemPrice;
}

public String getItemName() {
return itemName;
}

public void setItemName(String itemName) {
this.itemName = itemName;
}

public String getItemPrice() {
return itemPrice;
}

public void setItemPrice(String itemPrice) {
this.itemPrice = itemPrice;
}

}

}
}

activity_main.xml


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/linear_listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" />

</ScrollView>


row_first.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/linearFirst"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:padding="15dp" >

        <TextView
            android:id="@+id/textViewName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:text="TextView"
            android:textStyle="bold"
            android:textColor="@color/theme_color"
            android:textSize="17dp" />

        <ImageView
            android:id="@+id/imageFirstArrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="5dp" />
    </RelativeLayout>

     <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/theme_color" />
     
    <LinearLayout
        android:id="@+id/linear_scroll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:background="@android:color/white"
        android:orientation="vertical" />

</LinearLayout>


row_second.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/linearSecond"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white"
        android:padding="15dp" >

        <TextView
            android:id="@+id/textViewTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_marginLeft="10dp"
            android:text="TextView"
            android:textColor="#EC5B00"
            android:textStyle="bold"
            android:textSize="17dp" />

        <ImageView
            android:id="@+id/imageSecondArrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_marginRight="5dp" />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/theme_color" />
    
    <LinearLayout
        android:id="@+id/linear_scroll_third"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:background="@android:color/white"
        android:orientation="vertical" />
</LinearLayout>


row_third.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/white"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/white"
        android:orientation="horizontal"
        android:padding="15dp" >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/background_light"
            android:text="@string/right_arrow"
            android:textColor="@color/theme_color"
            android:layout_marginRight="5dp"
            android:textSize="17dp" />

        <TextView
            android:id="@+id/textViewItemName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/background_light"
            android:text="TextView"
            android:layout_weight="1"
            android:textColor="@color/theme_color"
            android:textSize="17dp" />

        <TextView
            android:id="@+id/textViewItemPrice"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@android:color/background_light"
            android:text="TextView"
            android:textColor="@android:color/black"
            android:textSize="17dp" />
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="@color/theme_color" />

</LinearLayout>


strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">3LVLExpList</string>
    <string name="hello_world">Hello world!</string>
    <string name="action_settings">Settings</string>

    <string name="right_arrow">&#9654;</string>
    <color name="theme_color">#016299</color>
</resources>


NOTE: You may get error if you don't add image for arw_down.png and arw_lt.png file in drawable folder.


Download Source Code


Monday, May 5, 2014

Contact List With Checkbox - Part 1




  • 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.