Showing posts with label inflate. Show all posts
Showing posts with label inflate. Show all posts

Monday, October 19, 2009

Android Contact Tutorial

Assumptions
1. You are using eclipse.
2. You know little bit about android application development.
3. You have installed the emulator.
4. You know little about ListView, ArrayAdapter, Custom ArrayAdapter, Custom ListView etc

Overview of Tutorial

We are going to use an activity which will show the both contact list and group list, using one list view and activity. Their navigation (from contact list to group list and same reverse ) through one single button like .

We will introduce three more buttons add , delete and edit
for addition, deletion and updation for both contact and group.
When user navigating contact list then, add, delete and edit button work for contact and same buttons for group when user navigating group.


For this all scenario (contact and group) we are using just one activity and one ListView

Filenames Hierarchy:

Project Name:
AndroidContact

Src file names:

contactAdapter.java
contactClass.java
createEditContact.java
createEditGroup.java
frmContactListActivty.java
groupAdapter.java
myClass.java


Drawable Resources
add.png
edit.png
groups.png
icon.png
remove.png
user.png


Layout Resources

contact_layout.xml
contact_list_layout.xml
group_layout.xml
row_contact_layout.xml
row_group_layout.xml



Your R.java file look like below:
/* AUTO-GENERATED FILE. DO NOT MODIFY.
*
* This class was automatically generated by the
* aapt tool from the resource data it found. It
* should not be modified by hand.
*/

package com.SERG.code;

public final class R {
public static final class attr {
}
public static final class drawable {
public static final int add=0x7f020000;
public static final int edit=0x7f020001;
public static final int groups=0x7f020002;
public static final int icon=0x7f020003;
public static final int remove=0x7f020004;
public static final int user=0x7f020005;
}
public static final class id {
public static final int ImageView01=0x7f05001b;
public static final int ImageView02=0x7f05001f;
public static final int LinearLayout01=0x7f050001;
public static final int LinearLayout02=0x7f05000e;
public static final int LinearLayout03=0x7f05001e;
public static final int LinearLayout04=0x7f050020;
public static final int ScrollView01=0x7f050000;
public static final int TextView01=0x7f05000c;
public static final int TextView02=0x7f050003;
public static final int btnAdd=0x7f050011;
public static final int btnCCancel=0x7f050010;
public static final int btnCOK=0x7f05000f;
public static final int btnDelete=0x7f050012;
public static final int btnEdit=0x7f050013;
public static final int btnGCancel=0x7f05001a;
public static final int btnGOK=0x7f050019;
public static final int btnGroup=0x7f050014;
public static final int cmbGroup=0x7f05000d;
public static final int lblCHeading=0x7f050002;
public static final int lblGHeading=0x7f050017;
public static final int lblGroup=0x7f050021;
public static final int lblName=0x7f05001c;
public static final int lblNum=0x7f05001d;
public static final int linearLayout03=0x7f050015;
public static final int lvContact=0x7f050016;
public static final int txtAdd=0x7f050009;
public static final int txtComments=0x7f05000b;
public static final int txtCompany=0x7f050006;
public static final int txtEmail=0x7f050007;
public static final int txtGroup=0x7f050018;
public static final int txtName=0x7f050004;
public static final int txtPhoneNo=0x7f050008;
public static final int txtTitle=0x7f050005;
public static final int txtWebsite=0x7f05000a;
}
public static final class layout {
public static final int contact_layout=0x7f030000;
public static final int contact_list_layout=0x7f030001;
public static final int group_layout=0x7f030002;
public static final int row_contact_layout=0x7f030003;
public static final int row_group_layout=0x7f030004;
}
public static final class string {
public static final int app_name=0x7f040001;
public static final int hello=0x7f040000;
}
}



Step 1:

First of all copy the images in android Drawable resources for add, delete, edit, groups, user, and icon

Step 2:
In step 2 we will create each xml files as mention in Layout Resources plus also the AndroidManifest.xml file too.

1. contact_list_layout.xml

< ?xml version="1.0" encoding="utf-8"?>
< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:id="@+id/LinearLayout01">

< LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_width="fill_parent">
< Button android:layout_gravity="left" android:layout_height="60px"
android:layout_width="60px" android:drawableTop="@drawable/add"
android:layout_marginRight="15px" android:id="@+id/btnAdd"
android:paddingTop="12px">
< Button android:layout_gravity="center_horizontal"
android:layout_height="60px" android:layout_width="60px"
android:drawableTop="@drawable/remove" android:layout_marginRight="15px"
android:id="@+id/btnDelete" android:paddingTop="12px">
< Button android:layout_gravity="center_horizontal"
android:drawableBottom="@drawable/edit" android:layout_height="60px"
android:layout_width="60px" android:layout_marginRight="15px"
android:id="@+id/btnEdit" android:paddingBottom="15px">
< Button android:layout_gravity="right" android:drawableBottom="@drawable/user"
android:layout_height="60px" android:layout_width="60px" android:id="@+id/btnGroup"
android:paddingBottom="15px">

< LinearLayout android:id="@+id/linearLayout03"
android:layout_height="fill_parent" android:layout_width="fill_parent">
< ListView android:layout_width="fill_parent" android:id="@+id/lvContact"
android:layout_height="fill_parent">





2. row_contact_layout.xml


< LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal">
< ImageView android:id="@+id/ImageView01"
android:layout_height="60px" android:layout_width="60px">
< LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="fill_parent" android:layout_height="60px"
android:orientation="vertical">
< TextView android:text="TextView01" android:layout_height="30px"
android:layout_width="fill_parent" android:gravity="center_vertical"
android:id="@+id/lblName">
< TextView android:text="TextView02" android:layout_height="30px"
android:layout_width="fill_parent" android:gravity="center_vertical"
android:id="@+id/lblNum">




3. row_group_layout.xml

< LinearLayout android:id="@+id/LinearLayout03"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal">
< ImageView android:layout_height="60px" android:layout_width="60px"
android:id="@+id/ImageView02">
< LinearLayout android:id="@+id/LinearLayout04"
android:layout_width="fill_parent" android:layout_height="60px"
android:orientation="vertical">
< TextView android:text="TextView01" android:layout_width="fill_parent"
android:gravity="center_vertical" android:layout_height="60px"
android:id="@+id/lblGroup">





4. contact_layout.xml

< ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
< LinearLayout android:id="@+id/LinearLayout01"
android:layout_height="wrap_content" android:orientation="vertical"
android:layout_width="fill_parent">
< TextView android:layout_height="wrap_content" android:id="@+id/lblCHeading"
android:layout_width="wrap_content">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Name : ">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtName">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Title : ">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtTitle">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Company : ">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtCompany">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="E Mail : ">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtEmail">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Phone Num : ">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtPhoneNo">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Address : ">
< EditText android:layout_width="fill_parent"
android:layout_height="100px" android:id="@+id/txtAdd">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Web Site :">
< EditText android:layout_height="wrap_content"
android:layout_width="fill_parent" android:id="@+id/txtWebsite">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Comments : ">
< EditText android:layout_width="fill_parent"
android:layout_height="100px" android:id="@+id/txtComments">
< TextView android:id="@+id/TextView01" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Group">
< Spinner android:layout_height="wrap_content" android:id="@+id/cmbGroup"
android:layout_width="fill_parent">
< LinearLayout android:id="@+id/LinearLayout02"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_width="fill_parent">
< Button android:layout_height="wrap_content" android:id="@+id/btnCOK"
android:text="Add Contact" android:layout_marginRight="30px"
android:layout_width="125px">
< Button android:layout_height="wrap_content" android:id="@+id/btnCCancel"
android:text="Cancel" android:layout_marginRight="30px"
android:layout_width="125px">







5. group_layout.xml

< LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical">
< TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/lblGHeading">
< TextView android:id="@+id/TextView02" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Group Name : "
android:layout_marginTop="50px" android:layout_marginBottom="10px">
< EditText android:layout_height="wrap_content" android:id="@+id/txtGroup"
android:layout_width="fill_parent" android:layout_marginBottom="10px"
android:singleLine="true">
< LinearLayout android:id="@+id/LinearLayout02"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:orientation="horizontal">
&alt Button android:layout_height="wrap_content" android:id="@+id/btnGOK"
android:text="Add Group" android:layout_marginLeft="30px"
android:layout_width="125px">
< Button android:layout_height="wrap_content" android:text="Cancel"
android:id="@+id/btnGCancel" android:layout_marginLeft="30px"
android:layout_width="125px">





6. AndroidManifest.xml

< ?xml version="1.0" encoding="utf-8"?>
< manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.SERG.code" android:versionCode="1" android:versionName="1.0">
< application android:icon="@drawable/icon" android:label="@string/app_name">
< activity android:name=".frmContactListActivty"
android:label="@string/app_name">
< intent-filter>
< action android:name="android.intent.action.MAIN" />
< category android:name="android.intent.category.LAUNCHER" />


< activity android:name=".createEditGroup">
< activity android:name=".createEditContact">

< uses-sdk android:minSdkVersion="3" />


Step3:
In step 3, we will create source files for above xml files.
1. contactAdapter.java

package com.SERG.code;

import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class contactAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
Bitmap bitContact;

public contactAdapter(Context context, int textViewResourceId,
List _items) {
super(context, textViewResourceId, _items);
mInflater = LayoutInflater.from(context);
bitContact = BitmapFactory.decodeResource(context.getResources(),
R.drawable.user);
}

static class ViewHolder {
TextView lblName, lblNum;
ImageView img;
}

public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary
// calls
// to findViewById() on each row.
ViewHolder holder;

// When convertView is not null, we can reuse it directly, there is no
// need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_contact_layout, null);

// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.lblName = (TextView) convertView.findViewById(R.id.lblName);
holder.lblNum = (TextView) convertView.findViewById(R.id.lblNum);
holder.img = (ImageView) convertView.findViewById(R.id.ImageView01);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
contactClass obj = getItem(position);
// Bind the data efficiently with the holder.
holder.lblName.setText(obj.getName());
holder.lblNum.setText(obj.getPhoneNo());
holder.img.setImageBitmap(bitContact);
// holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

return convertView;
}
}


2. groupAdapter.java
package com.SERG.code;

import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class groupAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
Bitmap bitGroup;

public groupAdapter(Context context, int textViewResourceId,
List _items) {
super(context, textViewResourceId, _items);
mInflater = LayoutInflater.from(context);
bitGroup = BitmapFactory.decodeResource(context.getResources(),
R.drawable.groups);
}

static class ViewHolder {
TextView lblGroup;
ImageView img;
}

public View getView(int position, View convertView, ViewGroup parent) {
// A ViewHolder keeps references to children views to avoid unneccessary
// calls
// to findViewById() on each row.
ViewHolder holder;

// When convertView is not null, we can reuse it directly, there is no
// need
// to reinflate it. We only inflate a new View when the convertView
// supplied
// by ListView is null.
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row_group_layout, null);

// Creates a ViewHolder and store references to the two children
// views
// we want to bind data to.
holder = new ViewHolder();
holder.lblGroup = (TextView) convertView
.findViewById(R.id.lblGroup);
holder.img = (ImageView) convertView.findViewById(R.id.ImageView02);
convertView.setTag(holder);
} else {
// Get the ViewHolder back to get fast access to the TextView
// and the ImageView.
holder = (ViewHolder) convertView.getTag();
}
String obj = getItem(position);
// Bind the data efficiently with the holder.
holder.lblGroup.setText(obj);
holder.img.setImageBitmap(bitGroup);
// holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);

return convertView;
}
}

3. frmContactListActivty.java
package com.SERG.code;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class frmContactListActivty extends Activity {
public ListView lvContactList;
public static contactAdapter adContact;
public static groupAdapter adGroup;
public static ArrayList strContact;
public static ArrayList strGroup;
Button btnAdd, btnDelete, btnEdit, btnGroup;
public String flag = "nothing", flagForButtonGroup = "nothing";
public static int index = -1;
public static final int MENU_SEARCH = Menu.FIRST;
public static int groupLocation;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("myTag", "before the setContentView");
setContentView(R.layout.contact_list_layout);
init();
btnAdd.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (flag.equals("contact")) {
Intent cIntent = new Intent(frmContactListActivty.this,
createEditContact.class);
cIntent.putExtra("flag", flag);
cIntent.putExtra("aFlag", "Add");
cIntent.putExtra("index", -1);
startActivity(cIntent);
} else if (flag.equals("group")) {
Intent gIntent = new Intent(frmContactListActivty.this,
createEditGroup.class);
gIntent.putExtra("flag", flag);
gIntent.putExtra("aFlag", "Add");
gIntent.putExtra("groupName", "Nothing");
startActivity(gIntent);
}
}
});// end of btnAdd
btnEdit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (index != -1) {
if (flag.equals("contact")) {
Intent cIntent = new Intent(frmContactListActivty.this,
createEditContact.class);
cIntent.putExtra("flag", flag);
cIntent.putExtra("aFlag", "Edit");
cIntent.putExtra("index", index);
// strGroup.indexOf(index);
// groupLocation=adGroup.getPosition(.toString);
startActivity(cIntent);
} else if (flag.equals("group")) {
Intent gIntent = new Intent(frmContactListActivty.this,
createEditGroup.class);
gIntent.putExtra("flag", flag);
gIntent.putExtra("aFlag", "Edit");
gIntent.putExtra("groupName", strGroup.get(index));
startActivity(gIntent);
}
}// end of index
else {
Toast.makeText(frmContactListActivty.this,
"First Select Item from List", Toast.LENGTH_SHORT)
.show();
}
}
});// end of btnEdit
btnDelete.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (index != -1) {
if (flag.equals("contact")) {
android.app.AlertDialog.Builder add = myDialog(
frmContactListActivty.this,
"Contact Deletion Confirmation",
"Are You Want to Delete Selected Contact", true);
add.show();
// adContact.notifyDataSetChanged();
} else if (flag.equals("group")) {
android.app.AlertDialog.Builder add = myDialog(
frmContactListActivty.this,
"Group Deletion Confirmation",
"Are You Want to Delete Selected Group", true);
add.show();
// adGroup.notifyDataSetChanged();
}
} else {
Toast.makeText(frmContactListActivty.this,
"First Select Item from List", Toast.LENGTH_SHORT)
.show();
}
}
});// end of btnGroup
btnGroup.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (flagForButtonGroup.equals("contact")) {
adContact.notifyDataSetChanged();
lvContactList.setAdapter(adContact);
index = -1;
flagForButtonGroup = "group";
flag = "contact";
} else if (flagForButtonGroup.equals("group")) {
adGroup.notifyDataSetChanged();
lvContactList.setAdapter(adGroup);
index = -1;
flagForButtonGroup = "contact";
flag = "group";
}

}
});// end of btnGroup(changes to group then back to contact)
lvContactList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView arg0, View arg1, int _index,
long arg3) {
index = _index;
Log.d("myTag", "index = " + index);

}
});// end of lvContactList(ListView) item click

}// end of onCreate method

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// create option menu
super.onCreateOptionsMenu(menu);
MenuItem menuAdd = menu
.add(0, MENU_SEARCH, Menu.NONE, "Search Contact");
return true;
}// end of onCreateOptionsMenu method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// handling of option menuitem
super.onOptionsItemSelected(item);
// int index = lvAlert.getSelectedItemPosition();
switch (item.getItemId()) {
case (MENU_SEARCH): {

return true;
}// END OF ADD
}// END OF SWITCH
return false;
}

private void init() {

strContact = new ArrayList();
strContact.add(new contactClass("ali", "", "", "", "03349069909", "",
"", "", "Family"));
strContact.add(new contactClass("mohsin", "", "", "", "03349069908",
"", "", "", "SERG"));
strContact.add(new contactClass("khan", "", "", "", "03349069907", "",
"", "", "Friend"));
strContact.add(new contactClass("shah", "", "", "", "03349069906", "",
"", "", "SERG"));
strContact.add(new contactClass("saleem", "", "", "", "03349069905",
"", "", "", "Family"));
strContact.add(new contactClass("sohail", "", "", "", "03349069904",
"", "", "", "SERG"));
strContact.add(new contactClass("nasir", "", "", "", "03349069903", "",
"", "", "SERG"));
strContact.add(new contactClass("tooqer", "", "", "", "03349069902",
"", "", "", "Friend"));
strContact.add(new contactClass("yasir", "", "", "", "033490699091",
"", "", "", "SERG"));
strContact.add(new contactClass("nouman", "", "", "", "03349069900",
"", "", "", "Friend"));
strGroup = new ArrayList();
strGroup.add("Family");
strGroup.add("Friend");
strGroup.add("SERG");
btnAdd = (Button) findViewById(R.id.btnAdd);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnEdit = (Button) findViewById(R.id.btnEdit);
btnGroup = (Button) findViewById(R.id.btnGroup);
Log.d("myTag", "before array adapter ");
adContact = new contactAdapter(frmContactListActivty.this,
android.R.layout.simple_list_item_1, strContact);
adGroup = new groupAdapter(frmContactListActivty.this,
R.layout.row_group_layout, strGroup);
lvContactList = (ListView) findViewById(R.id.lvContact);
lvContactList.setAdapter(adContact);
flag = "contact";
flagForButtonGroup = "group";
}// end of init method

public android.app.AlertDialog.Builder myDialog(
android.content.Context con, String title, String msg,
boolean cancelButton) {
// user define function for creating dialog box and handling its button
// events
android.app.AlertDialog.Builder ad = new android.app.AlertDialog.Builder(
con);
ad.setTitle(title);
ad.setMessage(msg);
ad.setNegativeButton("No",
new android.content.DialogInterface.OnClickListener() {
public void onClick(android.content.DialogInterface di,
int args) {
NBMethod();
}
});
ad.setPositiveButton("Yes",
new android.content.DialogInterface.OnClickListener() {
public void onClick(android.content.DialogInterface di,
int args) {
PBMethod();
}
});
if (cancelButton == true) {
ad.setCancelable(true);
ad
.setOnCancelListener(new android.content.DialogInterface.OnCancelListener() {
public void onCancel(android.content.DialogInterface d) {
CBMethod();
}
});
// End of If Body
}
return ad;
}// end of myDialog method

public void NBMethod() {
// Implementation of Negative Button Click Event of dialogBox
index = -1;
}// end of NBMethod

public void PBMethod() {
// Implementation of Positive Button Click Event of dialogBox
// delete record from remote database and then from ListView

if (index != -1) {
if (flag.equals("contact")) {
strContact.remove(index);
adContact.notifyDataSetChanged();
} else if (flag.equals("group")) {
strGroup.remove(index);
adGroup.notifyDataSetChanged();
}
} else {
Toast.makeText(frmContactListActivty.this,
"Select the item from List", Toast.LENGTH_SHORT).show();
}
index = -1;

}// end of PBMethod

public void CBMethod() {
index = -1;
}// end of CBMethod
}// end of frmContactListActivty class


4. contactClass.java
package com.SERG.code;

public class contactClass {

String name;
String title;
String company;
String email;
String phoneno;
String add;
String website;
String comments;
String group;
contactClass(
String _name,
String _title,
String _company,
String _email,
String _phoneno,
String _add,
String _website,
String _comments,
String _group
){
name=_name;
title=_title;
company=_company;
email=_email;
phoneno=_phoneno;
add=_add;
website=_website;
comments=_comments;
group=_group;
}
public String getName(){ return name; }
public String getTitle(){ return title; }
public String getCompany(){ return company; }
public String getEmail(){ return email; }
public String getPhoneNo(){ return phoneno; }
public String getAdd(){ return add; }
public String getWebsite(){ return website; }
public String getComments(){ return comments; }
public String getGroup(){ return group; }
@Override
public String toString(){

return name + " " + phoneno;
}
}

5. createEditContact.java
package com.SERG.code;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class createEditContact extends Activity {
TextView lblCHeading;
EditText txtName, txtTitle, txtCompany, txtEmail, txtPhoneNo, txtAddress,
txtWebsite, txtComments;
Spinner cmbGroup;
Button btnCOK, btnCCancel;
String aFlag;
int index;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.contact_layout);
init();
ArrayAdapter adpGroup = new ArrayAdapter(
createEditContact.this, android.R.layout.simple_spinner_item,
frmContactListActivty.strGroup);
cmbGroup.setAdapter(adpGroup);
Intent in = getIntent();
Bundle data = in.getExtras();
String flag = data.getString("flag");
aFlag = data.getString("aFlag");
index = data.getInt("index", -1);
if (flag.equals("contact")) {
if (aFlag.equals("Add")) {
lblCHeading.setText("Add New Contact");
btnCOK.setText("Add Contact");
}// end of Add if
else if (aFlag.equals("Edit")) {
lblCHeading.setText("Edit Contact");
contactClass cObj = frmContactListActivty.strContact.get(index);
txtName.setText(cObj.getName());
txtTitle.setText(cObj.getTitle());
txtCompany.setText(cObj.getCompany());
txtEmail.setText(cObj.getEmail());
txtPhoneNo.setText(cObj.getPhoneNo());
txtAddress.setText(cObj.getAdd());
txtWebsite.setText(cObj.website);
txtComments.setText(cObj.comments);
cmbGroup.setSelection(adpGroup.getPosition(cObj.getGroup()));
btnCOK.setText("Update Contact");
}// end of Edit If
}// end of group if

btnCOK.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Boolean bName = (txtName.getText() == null || txtName.getText()
.toString().equals(""));
Boolean bTitle = (txtTitle.getText() == null || txtTitle
.getText().toString().equals(""));
Boolean bCompanay = (txtCompany.getText() == null || txtCompany
.getText().toString().equals(""));
Boolean bEmail = (txtEmail.getText() == null || txtEmail
.getText().toString().equals(""));
Boolean bPhoneNo = (txtPhoneNo.getText() == null || txtPhoneNo
.getText().toString().equals(""));
Boolean bAddress = (txtAddress.getText() == null || txtAddress
.getText().toString().equals(""));
Boolean bWebsite = (txtWebsite.getText() == null || txtWebsite
.getText().toString().equals(""));
Boolean bComments = (txtComments.getText() == null || txtComments
.getText().toString().equals(""));
if (index != -1) {
if (!(bName || bPhoneNo)) {
if (aFlag.equals("Add")) {
contactClass cObj = new contactClass(txtName
.getText().toString(), (bTitle ? ""
: txtTitle.getText().toString()),
(bCompanay ? "" : txtCompany.getText()
.toString()), (bEmail ? ""
: txtEmail.getText().toString()),
txtPhoneNo.getText().toString(),
(bAddress ? "" : txtAddress.getText()
.toString()), (bWebsite ? ""
: txtWebsite.getText().toString()),
(bComments ? "" : txtComments.getText()
.toString()), cmbGroup
.getSelectedItem().toString());
frmContactListActivty.strContact.add(cObj);
frmContactListActivty.adContact
.notifyDataSetChanged();
Toast.makeText(createEditContact.this,
"New Contact Added", Toast.LENGTH_SHORT)
.show();
index = -1;
finish();
}// end of Add if
else if (aFlag.equals("Edit")) {
frmContactListActivty.strContact.remove(index);
contactClass cObj = new contactClass(txtName
.getText().toString(), (bTitle ? ""
: txtTitle.getText().toString()),
(bCompanay ? "" : txtCompany.getText()
.toString()), (bEmail ? ""
: txtEmail.getText().toString()),
txtPhoneNo.getText().toString(),
(bAddress ? "" : txtAddress.getText()
.toString()), (bWebsite ? ""
: txtWebsite.getText().toString()),
(bComments ? "" : txtComments.getText()
.toString()), cmbGroup
.getSelectedItem().toString());
frmContactListActivty.strContact.add(index, cObj);
frmContactListActivty.adContact
.notifyDataSetChanged();
Toast.makeText(createEditContact.this,
"Contact Updated", Toast.LENGTH_SHORT)
.show();
index = -1;
finish();
}// end of Edit If
}// end of bName and bPhone if
else {
Toast
.makeText(createEditContact.this,
"Name and Phone is Missing",
Toast.LENGTH_SHORT).show();
}
}// end of index if
}
});// end of btnGOK
btnCCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});// end of btnGCancel

}// end of onCreate Method

private void init() {
lblCHeading = (TextView) findViewById(R.id.lblCHeading);
txtName = (EditText) findViewById(R.id.txtName);
txtTitle = (EditText) findViewById(R.id.txtTitle);
txtCompany = (EditText) findViewById(R.id.txtCompany);
txtEmail = (EditText) findViewById(R.id.txtEmail);
txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtAddress = (EditText) findViewById(R.id.txtAdd);
txtWebsite = (EditText) findViewById(R.id.txtWebsite);
txtComments = (EditText) findViewById(R.id.txtComments);
cmbGroup = (Spinner) findViewById(R.id.cmbGroup);
btnCOK = (Button) findViewById(R.id.btnCOK);
btnCCancel = (Button) findViewById(R.id.btnCCancel);
}// end of init method

}// end of createEditContact

6. createEditGroup.java
package com.SERG.code;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class createEditGroup extends Activity {
EditText txtGroup;
String aFlag;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.group_layout);
TextView lblGHeading = (TextView) findViewById(R.id.lblGHeading);
txtGroup = (EditText) findViewById(R.id.txtGroup);
Button btnGOK = (Button) findViewById(R.id.btnGOK);
Button btnGCancel = (Button) findViewById(R.id.btnGCancel);
Intent in = getIntent();
Bundle data = in.getExtras();
String flag = data.getString("flag");
aFlag = data.getString("aFlag");
String groupName = data.getString("groupName");
if (flag.equals("group")) {
if (aFlag.equals("Add")) {
lblGHeading.setText("Add New Group");
btnGOK.setText("Add Group");
}// end of Add if
else if (aFlag.equals("Edit")) {
lblGHeading.setText("Edit Group");
txtGroup.setText(groupName);
btnGOK.setText("Update Group");
}// end of Edit If
}// end of group if
btnGOK.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (!(txtGroup.getText() == null || txtGroup.getText()
.toString().equals(""))) {
if (aFlag.equals("Add")) {
frmContactListActivty.strGroup.add(txtGroup.getText()
.toString());
frmContactListActivty.adGroup.notifyDataSetChanged();
frmContactListActivty.adGroup.notifyDataSetChanged();
Toast.makeText(createEditGroup.this,
"New Group Created", Toast.LENGTH_SHORT).show();
finish();
}// end of Add if
else if (aFlag.equals("Edit")) {
frmContactListActivty.strGroup
.remove(frmContactListActivty.index);
frmContactListActivty.strGroup.add(
frmContactListActivty.index, txtGroup.getText()
.toString());
frmContactListActivty.adGroup.notifyDataSetChanged();
Toast.makeText(createEditGroup.this, "Group Updated",
Toast.LENGTH_SHORT).show();
frmContactListActivty.index = -1;
finish();
}// end of Edit If
}// end of txtGroup if
else {
Toast.makeText(createEditGroup.this, "Group is Missing",
Toast.LENGTH_SHORT).show();
}
}
});// end of btnGOK
btnGCancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});// end of btnGCancel
}// end of onCreate Method
}

Some snaps are below:









Wednesday, October 14, 2009

Inflation is a Good Thing

Before diving into the topic of creating fancy lists in Android, we need to take a short detour into some background material. If you have written activities for Android, you are used to calling setContentView() with the resource ID of some XML layout you specified. Let’s take a peek at how that is probably implemented: via a technique called “view inflation”.

In this case, “inflation” means the act of converting an XML layout specification into the actual tree of View objects the XML represents. This is undoubtedly a tedious bit of code: take an element, create an instance of the specified View class, walk the attributes, convert those into property setter calls, iterate over all child elements, lather, rinse, repeat.

The good news is that the fine folk on the Android team wrapped all that up into a class called ViewInflate that we can use ourselves. When it comes to fancy lists, for example, we will want to inflate Views for each row shown in the list, so we can use the convenient shorthand of the XML layout to describe what the rows are supposed to look like.

For example, here is your typical do-nothing activity, except re-written to use ViewInflate instead of supplying the resource ID to setContentView():

public class InflaterDemo extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

setContentView(getViewInflate().inflate(R.layout.main, null, null));

// setContentView(R.layout.main);
}
}

Your activity can get an appropriate instance of ViewInflate via getViewInflate(). Then, to convert a resource ID into a View tree, just call inflate() with the resource ID in question. That gives you your View; in this case, we pass the View to setContentView(), as if we had instantiated the View manually.

Fancy ListViews, Part One

The classic Android ListView is a plain list of text — solid but uninspiring. we will see how to create a ListView with a bit more pizazz. Today, in particular, we will see two techniques for creating a ListView whose rows contain icons, in addition to text.

If you want rows to have a different look than the stock r ows, one way to accomplish this is to supply your own layout XML to be used for each row, telling Android to use your layout rather than one of the built-in ones. This gives you complete control over what goes in the row and how it is laid out.
For example, suppose you want a ListView whose entries are made up of an icon, followed by some text. You could construct a layout for the row that looks like this:

01.02. android:layout_width="fill_parent"
03. android:layout_height="wrap_content"
04. android:orientation="horizontal"
05.>
06. 07. android:id="@+id/icon"
08. android:layout_width="22px"
09. android:paddingLeft="2px"
10. android:paddingRight="2px"
11. android:paddingTop="2px"
12. android:layout_height="wrap_content"
13. android:src="@drawable/ok"
14. />
15. 16. android:id="@+id/label"
17. android:layout_width="wrap_content"
18. android:layout_height="wrap_content"
19. android:textSize="44sp"
20. />
21.

This layout uses a LinearLayout to set up a row, with the icon on the left and the text (in a nice big font) on the right.
By default, though, Android has no idea that you want to use this layout with your ListView. To make the connection, you need to supply your Adapter with the resource ID of your custom layout:

01.public class StaticDemo extends ListActivity {
02. TextView selection;
03. String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
04. "consectetuer", "adipiscing", "elit", "morbi", "vel",
05. "ligula", "vitae", "arcu", "aliquet", "mollis",
06. "etiam", "vel", "erat", "placerat", "ante",
07. "porttitor", "sodales", "pellentesque", "augue",
08. "purus"};
09.
10. @Override
11. public void onCreate(Bundle icicle) {
12. super.onCreate(icicle);
13. setContentView(R.layout.main);
14. setListAdapter(new ArrayAdapter(this,
15. R.layout.row, R.id.label,
16. items));
17. selection=(TextView)findViewById(R.id.selection);
18. }
19.
20. public void onListItemClick(ListView parent, View v,int position, long id) {
21. selection.setText(items[position]);
22. }
23.}
Displays a list of random words, and puts the currently-selected word in a TextView.

The key in this example is that you have told ArrayAdapter that you want to use your custom layout (R.layout.row) and that the TextView where the word should go is known as R.id.label within that custom layout.
The result is a ListView with icons down the left side. In particular, all the icons are the same.
This technique — supplying an alternate layout to use for rows — handles simple cases very nicely. However, it falls down when you have more complicated scenarios for your rows, such as:
• Not every row uses the same layout (e.g., some have one line of text, others have two)
• You need to configure the widgets in the rows (e.g., different icons for different cases)
In those cases, the better option is to create your own subclass of your desired Adapter, override getView(), and construct your rows yourself. The getView() method is responsible for returning a View, representing the row for the supplied position in the adapter data.
For example, let’s rework the above code to use getView(), so we can have different icons for different rows — in this case, one icon for short words and one for long words:

01.public class DynamicDemo extends ListActivity {
02. TextView selection;
03. String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
04. "consectetuer", "adipiscing", "elit", "morbi", "vel",
05. "ligula", "vitae", "arcu", "aliquet", "mollis",
06. "etiam", "vel", "erat", "placerat", "ante",
07. "porttitor", "sodales", "pellentesque", "augue",
08. "purus"};
09.
10. @Override
11. public void onCreate(Bundle icicle) {
12. super.onCreate(icicle);
13. setContentView(R.layout.main);
14. setListAdapter(new IconicAdapter(this));
15. selection=(TextView)findViewById(R.id.selection);
16. }
17.
18. public void onListItemClick(ListView parent, View v, int position, long id) {
19. selection.setText(items[position]);
20. }
21.
22. class IconicAdapter extends ArrayAdapter {
23. Activity context;
24.
25. IconicAdapter(Activity context) {
26. super(context, R.layout.row, items);
27.
28. this.context=context;
29. }
30.
31. public View getView(int position, View convertView, ViewGroup parent) {
32. ViewInflate inflater=context.getViewInflate();
33. View row=inflater.inflate(R.layout.row, null, null);
34. TextView label=(TextView)row.findViewById(R.id.label);
35.
36. label.setText(items[position]);
37.
38. if (items[position].length()>4) {
39. ImageView icon=(ImageView)row.findViewById(R.id.icon);
40.
41. icon.setImageResource(R.drawable.delete);
42. }
43.
44. return(row);
45. }
46. }
47.}
In our getView() implementation, we first get our hands on a ViewInflate object so we can use it to “inflate” our row layout XML and give us a View representing that row.
Then, we tailor that View to match our needs:
• We fill in the text label into our label widget, using the word at the supplied position
• We see if the word is longer than four characters and, if so, we find our ImageView icon widget and replace the stock resource with a different one
Now, we have a ListView with different icons based upon context of that specific entry in the list. Obviously, this was a fairly contrived example, but you can see where this technique could be used to customize rows based on any sort of criteria, such as other columns in a returned Cursor.