Sei sulla pagina 1di 11

It isn’t complicated, is it?

As you see, every item in the list view contains an image and 3 lines of text
indicating Name, Phone Number and Email Address.

Ok, so let’s start to create!

A – Create The Project


Project Name: Phone Book
Application Name: Phone Book

Package Name: pete.android.study

Create Activity: MainActivity

Min SDK: 10

Click OK -> Done with creating project.

B – Sketching The Layout


As you see in the image above, apparently, we need two layouts.

+ One layout for main screen display, which is the list view

+ One layout for each item in the list view, which will be set to list view

First, we start with layout for each item in list view.

1. List Item Layout


What we have in here? The profile avatar on the left of the list item, we will use a ImageView control
to display.

On the right, there are three lines of text, one is for Name, one for Mobile Number and the other for
Email Address.

Of course, we can use just one single TextView to display all three lines but in my opinion, it would be
very inconvenient when we need to reset data text to display on one of these three lines. So, it’s
better to use 3 TextView controls, one for each.

For layout display, we need one layout container for 3 lines of text and one layout container for the
ImageView and the other layout container (containing 3 TextView).

Hence, the final layout will be like this:

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<ImageView
android:id="@+id/imgAvatar"
android:layout_width="70dip"
android:layout_height="70dip"
android:scaleType="fitCenter"
/>

<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>

<TextView
android:id="@+id/tvName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
/>

<TextView
android:id="@+id/tvPhone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

<TextView
android:id="@+id/tvEmail"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>

</LinearLayout>

2. Main Layout
Simply, just one ListView to display all items.

<?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">

<ListView
android:id="@+id/listPhone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>

C – Class Design: On the Idea


Class Diagram
D – From Design to Coding
1. PhoneBook: the entity class which holds the information: avatar bitmap, name, phone, email.

package pete.android.study;

import android.graphics.Bitmap;

public class PhoneBook {


private Bitmap mAvatar;
private String mName;
private String mPhone;
private String mEmail;

public PhoneBook(Bitmap avatar, String name, String phone, String email) {


mAvatar = avatar;
mName = name;
mPhone = phone;
mEmail = email;
}

public void setAvatar(Bitmap avatar) {


mAvatar = avatar;
}
public Bitmap getAvatar() {
return mAvatar;
}

public void setName(String name) {


mName = name;
}
public String getName() {
return mName;
}

public void setPhone(String phone) {


mPhone = phone;
}
public String getPhone() {
return mPhone;
}

public void setEmail(String email) {


mEmail = email;
}
public String getEmail() {
return mEmail;
}
}

2. PhoneBookAdapter: the adapter used to handle data when it is changed. However, I’ve just
wanted to show how to create the custom list view, so I won’t mention about handling list item data.

package pete.android.study;

import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class PhoneBookAdapter extends BaseAdapter {


private Context mContext;
private List<PhoneBook> mListPhoneBook;

public PhoneBookAdapter(Context context, List<PhoneBook> list) {


mContext = context;
mListPhoneBook = list;

@Override
public int getCount() {
return mListPhoneBook.size();
}
@Override
public Object getItem(int pos) {
return mListPhoneBook.get(pos);
}

@Override
public long getItemId(int pos) {
return pos;
}

@Override
public View getView(int pos, View convertView, ViewGroup parent) {
// get selected entry
PhoneBook entry = mListPhoneBook.get(pos);

// inflating list view layout if null


if(convertView == null) {
LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(R.layout.phonebook_row, null);
}

// set avatar
ImageView ivAvatar =
(ImageView)convertView.findViewById(R.id.imgAvatar);
ivAvatar.setImageBitmap(entry.getAvatar());

// set name
TextView tvName = (TextView)convertView.findViewById(R.id.tvName);
tvName.setText(entry.getName());

// set phone
TextView tvPhone = (TextView)convertView.findViewById(R.id.tvPhone);
tvPhone.setText(entry.getPhone());

// set email
TextView tvEmail = (TextView)convertView.findViewById(R.id.tvEmail);
tvEmail.setText(entry.getEmail());
return convertView;
}

3. MainActivity: this is the entry point of application to create and display the list, which will
use “<<override>>onCreate()” method.

package pete.android.study;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends Activity {

private ListView lvPhone;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

lvPhone = (ListView)findViewById(R.id.listPhone);

List<PhoneBook> listPhoneBook = new ArrayList<PhoneBook>();


listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.avatar_pete),
"Pete Houston", "010-9817-6331", "pete.houston.17187@gmail.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(), R.drawable.avatar_lina),
"Lina Cheng", "046-7764-1142", "lina.cheng011@sunny.com"));
listPhoneBook.add(new PhoneBook(
BitmapFactory.decodeResource(getResources(),
R.drawable.avatar_jenny),
"Jenny Nguyen", "0913-223-498", "jenny_in_love98@yahoo.com"));
PhoneBookAdapter adapter = new PhoneBookAdapter(this, listPhoneBook);
lvPhone.setAdapter(adapter);
}
}

E – Note
- The image display in the ImageView is scaled by setting in the layout, which uses “dip” unit.

- Use BitmapFactory.decodeFromResource() to create a bitmap from resource.


- Always use an adapter to use in the ListView to handle data change events (display, add, remove…).
However, I don’t mention about it here. Just remember it!

F – Get The Project Created by Pete


Pick your favorite hosting server: Mediafire | Rapidshare | FreeFileHosting

G – Final Words
- Did you learn something from this?

- Hope you enjoy it

Insert an item to contacts:

Collapse | Copy Code


public static void Insert2Contacts(Context ctx, String nameSurname,
String telephone) {
if (!isTheNumberExistsinContacts(ctx, telephone)) {
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
int rawContactInsertIndex = ops.size();

ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)
.withValue(RawContacts.ACCOUNT_TYPE, null)
.withValue(RawContacts.ACCOUNT_NAME, null).build());
ops.add(ContentProviderOperation
.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(
ContactsContract.Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)
.withValue(Phone.NUMBER, telephone).build());
ops.add(ContentProviderOperation
.newInsert(Data.CONTENT_URI)
.withValueBackReference(Data.RAW_CONTACT_ID,
rawContactInsertIndex)
.withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)
.withValue(StructuredName.DISPLAY_NAME, nameSurname)
.build());
try {
ContentProviderResult[] res = ctx.getContentResolver()
.applyBatch(ContactsContract.AUTHORITY, ops);
} catch (Exception e) {

Log.d(TAG, e.getMessage());
}
}
}

Search an item inside contacts:

Collapse | Copy Code


public static boolean isTheNumberExistsinContacts(Context ctx,
String phoneNumber) {
Cursor cur = null;
ContentResolver cr = null;

try {
cr = ctx.getContentResolver();

} catch (Exception ex) {


Log.d(TAG, ex.getMessage());
}

try {
cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null,
null, null);
} catch (Exception ex) {
Log.i(TAG, ex.getMessage());
}

try {
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));
// Log.i("Names", name);
if (Integer
.parseInt(cur.getString(cur
.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)))
> 0) {
// Query phone here. Covered next
Cursor phones = ctx
.getContentResolver()
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,

ContactsContract.CommonDataKinds.Phone.CONTACT_ID
+ " = " + id, null, null);
while (phones.moveToNext()) {
String phoneNumberX = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
// Log.i("Number", phoneNumber);

phoneNumberX = phoneNumberX.replace(" ", "");


phoneNumberX = phoneNumberX.replace("(", "");
phoneNumberX = phoneNumberX.replace(")", "");
if (phoneNumberX.contains(phoneNumber)) {
phones.close();
return true;

}
phones.close();
}

}
}
} catch (Exception ex) {
Log.i(TAG, ex.getMessage());

return false;
}

Delete an item from contacts:

Collapse | Copy Code


public static boolean deleteContact(Context ctx,String phoneNumber) {
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNumber));
Cursor cur = ctx.getContentResolver().query(contactUri, null, null,
null, null);
try {
if (cur.moveToFirst()) {
do {
String lookupKey =

cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(
ContactsContract.Contacts.CONTENT_LOOKUP_URI,
lookupKey);
ctx.getContentResolver().delete(uri, null, null);
} while (cur.moveToNext());
}

} catch (Exception e) {
System.out.println(e.getStackTrace());
}
return false;
}

}
Using the functions in the Contact Operation
Class
Collapse | Copy Code
ContactOperations.Insert2Contacts(getApplicationContext(),"Yildirim Kocdag", "05321000000");
if (ContactOperations.isTheNumberExistsinContacts(getApplicationContext(), "05321000000")) {
Log.i(ContactOperations.TAG, "Exists");
} else {
Log.i(ContactOperations.TAG, "Not Exists");
}

ContactOperations.deleteContact(getApplicationContext(), "05321000000");
if (ContactOperations.isTheNumberExistsinContacts(getApplicationContext(), "05321000000")) {
Log.i(ContactOperations.TAG, "Exists");
} else {
Log.i(ContactOperations.TAG, "Not Exists");
}

Do not forget to use appropriate permissions


in the AndroidManifest
The Read from Contact and Write to Contact permissions should be inside AndroidManifest.xml.

Collapse | Copy Code


<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>

Potrebbero piacerti anche