Displaying Contact Number and Contact Name in a Custom List View

Displaying Contact Number and Contact Name in a custom list view

Since op asked for the solution using custom adapter i have posted the below.(from the comments)

Display.java

public class Display extends Activity implements OnItemClickListener{

List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);

getAllContacts(this.getContentResolver());
ListView lv= (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener()
{

@Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++)

{
if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");

}
else
{
System.out.println("Not Checked......"+name1.get(i).toString());
}

}

Toast.makeText(Display.this, checkedcontacts,1000).show();
}
});

}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}

public void getAllContacts(ContentResolver cr) {

Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}

phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)Display.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub

return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);

return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}

public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}

public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

display.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"

android:id="@+id/lv"/>

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Select" />

</RelativeLayout>

Explanation:

The above uses a Custom Adapter. A custom layout row.xml with 2 textviews and one checkbox is inflated for each row. getAllContacts() will get all contacts from the contacts list and you store them in a list.

Custom Adapter displays the items in a custom layout inflated for each row.

When you check the check box and click display displays a toast with selected contacts name.

Snap shot

Sample Image

Displaying two Contact Numbers and Contact Name in a same row of custom list view

Here if you want to display example 50 Contact no in 25 row then first set items.size()/2 in getcount here also check odd even sequence if 51 contact no present then 26 row needed so
if(items.size()%2==0){
size=items.size()/2;
else{
size=(items.size()/2)+1;
}

and then in every row take two textview for contact name and two textview for contact no and set it

objBean = items.get(position);
objBean2 = items.get(position+1);

textview1.settext(objBean.getName());
textview2.settext(objBean.getPhoneNo());

textview3.settext(objBean2.getName());
textview4.settext(objBean2.getPhoneNo());

thats it..

I have to Display Contacts info (Name, Number, Image) of all contacts in a List View, using custom adapter which extends base adapter

I guess the problem is here:

image.setImageURI(Uri.parse(temp.image));

If your contact has no image, you are trying to parse a null.

I am not 100% sure but as you havn't provided any stack trace I guess this is the problem.

how to display contacts in a listview in Android for Android api 11+

Small stripped down example for displaying the contacts name in a ListView.
Below Fragment extends ListFragment which has a default layout. You don't need to specify your own. The layout for list items is also taken from Android's default layouts (android.R.layout.simple_list_item_1) which is a simple single line of text per item.

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;

public class ContactListFragment extends ListFragment implements LoaderCallbacks<Cursor> {

private CursorAdapter mAdapter;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// create adapter once
Context context = getActivity();
int layout = android.R.layout.simple_list_item_1;
Cursor c = null; // there is no cursor yet
int flags = 0; // no auto-requery! Loader requeries.
mAdapter = new SimpleCursorAdapter(context, layout, c, FROM, TO, flags);
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

// each time we are started use our listadapter
setListAdapter(mAdapter);
// and tell loader manager to start loading
getLoaderManager().initLoader(0, null, this);
}

// columns requested from the database
private static final String[] PROJECTION = {
Contacts._ID, // _ID is always required
Contacts.DISPLAY_NAME_PRIMARY // that's what we want to display
};

// and name should be displayed in the text1 textview in item layout
private static final String[] FROM = { Contacts.DISPLAY_NAME_PRIMARY };
private static final int[] TO = { android.R.id.text1 };

@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {

// load from the "Contacts table"
Uri contentUri = Contacts.CONTENT_URI;

// no sub-selection, no sort order, simply every row
// projection says we want just the _id and the name column
return new CursorLoader(getActivity(),
contentUri,
PROJECTION,
null,
null,
null);
}

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
// Once cursor is loaded, give it to adapter
mAdapter.swapCursor(data);
}

@Override
public void onLoaderReset(Loader<Cursor> loader) {
// on reset take any old cursor away
mAdapter.swapCursor(null);
}
}

Android: Set contact photo in a ListView with name and number

I figured it out. If someone had the same problem, this is how i did it:

In an activity that extends ListActivity:

    @Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Cursor names = getNamesAndPictures();
names.moveToFirst();
ListAdapter adapter = new MySimpleCursorAdapter(this, R.layout.contacts,
names, new String[] {Phones.NAME, Phones.NUMBER}, new int[] {
R.id.Nombre, R.id.Numero});
setListAdapter(adapter);
startManagingCursor(names);
Log.i(DEBUG_TAG, "Mi numero: " + miNumeroTelefono());
}

public Cursor getNamesAndPictures(){
String[] projection = new String[] {
Phones.NUMBER,
Phones.PERSON_ID,
People.NAME,
People._ID
};
String selection = Phones.NAME + "!='null'";
String sortOrder = Phones.NAME + " COLLATE LOCALIZED ASC";
Cursor cursor = managedQuery(Phones.CONTENT_URI, projection, selection, null, sortOrder);
return cursor;
}

In a custom adapter:

public class MySimpleCursorAdapter extends SimpleCursorAdapter {

...

@Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView imageView = (ImageView) view.findViewById(R.id.Foto);

int id = cursor.getColumnIndex(Phones.PERSON_ID);
Uri uri = ContentUris.withAppendedId(Phones.CONTENT_URI, cursor.getLong(id));
String uriPhoto = uri.toString();
String uriPeople = uriPhoto.replace("phones", "people");

Uri uriFinal = Uri.parse(uriPeople);

Bitmap bitmap = People.loadContactPhoto(context, uriFinal, R.drawable.avatar02, null);
imageView.setImageBitmap(bitmap);
super.bindView(view, context, cursor);
}
}

Select Contact from ListView and get their phone numbers in Android

A custom adapter is used here and finally it is working perfect. My next move will be implementing Check all check boxes button in it.

Upload_contact.java

public class disusa extends ListActivity implements OnItemClickListener{

List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma ;
Button select;
private boolean csv_status = false;
ToggleButton rdb;
ListView lv;

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

getAllContacts(this.getContentResolver());
rdb=(ToggleButton)findViewById(R.id.all);
//lv= (ListView) findViewById(R.id.);
lv = getListView();

ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);

select.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v) {
StringBuilder checkedcontacts= new StringBuilder();
//System.out.println(".............."+ma.mCheckStates.size());
for(int i = 0; i < name1.size(); i++){

if(ma.mCheckStates.get(i)==true)
{
checkedcontacts.append(phno1.get(i).toString());
checkedcontacts.append("\n");

CSVWriter writer = null;

try {

writer = new CSVWriter(new FileWriter(Environment.getExternalStorageDirectory().getAbsolutePath() + "/my_test_contact.csv"));

} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

writer.writeColumnNames(); // Write column header

if(phno1!=null) {

writer.writeNext((checkedcontacts.toString().split("\n")));

csv_status = true;

} else {

csv_status = false;

}

try {
if(writer != null)
writer.close();

} catch (IOException e) {
Log.w("Test", e.toString());
}

}
else
{
System.out.println("Not Checked......"+name1.get(i).toString());
}

}

Toast.makeText(disusa.this, checkedcontacts,1000).show();
}
});

rdb.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

if(rdb.isChecked()){
rdb.setBackgroundColor(Color.parseColor("#FBE039"));
rdb.setTextColor(Color.parseColor("#000000"));
for (int i = 0; i < lv.getChildCount(); i++)
getListView().setItemChecked(i, true);
Toast.makeText(disusa.this, "adios",1000).show();

}
else{
rdb.setBackgroundColor(Color.parseColor("#333333"));
rdb.setTextColor(Color.parseColor("#ffffff"));
for (int i = 0; i < lv.getCount(); i++)
getListView().setItemChecked(i, false);

Toast.makeText(disusa.this,"soida",1000).show();
}
}
});

}
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}

public void getAllContacts(ContentResolver cr) {

Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext())
{
String name=phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// System.out.println(".................."+phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}

phones.close();
}

class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter()
{
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater)disusa.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub

return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.contact_name);
tv1= (TextView) vi.findViewById(R.id.phone_number);
cb = (CheckBox) vi.findViewById(R.id.checkBox_id);
tv.setText("Name :"+ name1.get(position));
tv1.setText("Phone No :"+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);

return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}

public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}

public void toggle(int position) {
setChecked(position, !isChecked(position));
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub

mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
public View getView2(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return null;
}
}
}

reference = "Displaying Contact Number and Contact Name in a custom list view"



Related Topics



Leave a reply



Submit