الفكرة
برنامج لحفظ الاسماء مع رقم الهاتف والبريد الالكتروني والعنوان.
الشكل المقترح
الشاشة الرئيسية
شاشة تحتوي قائمة بجميع اسماء الاشخاص عند الضغط على الاسم تعرض الشاشة الثانية التي تمكننا من تعديل بيانات الشخص.
كما تحتوي قائمة من الخيارات كـ اضافة (Add) و بحث (Search) واعدادات (Settings).
شاشة الاضافة والتعديل
شاشة تحتوي نموذج (مجموعة من مربعات الادخال) تحتوي الاسم الاول والاسم الاخير ورقم الهاتف والبريد الالكتروني والعنوان وكما تحتوي زري الحفظ (Save) والالغاء (Discard).
الخطوط الرئيسية للمشروع
بناءا على التصور السابق سنستخدم في هذا المشروع:
- قاعدة بيانات SQLite.
- واجهات XML.
- قوائم خيارات XML.
- عناصر Activity و ListActivity.
- Views مكونات الواجهة: ListView, TextView, EditText, Button.
- Intents: لارسال البيانات بين الشاشة الرئيسية وشاشة التعديل.
Class Diagram
ERD
البدء في كتابة التطبيق
تشغيل eclipse.
انشاء مشروع Android من قائمة File>New>Other.
اختر Android Project.
اكتب اسم المشروع Project Name.
نختار اصدارة 2.1 حزمة التطوير هي نفسها اصدارة النظام.
اكتب البيانات.

Application Name: اسم التطبيق Address Book
Package Name: اسم الحزمة سمها ما تشاء. انا اخترت abdullah.android.addressbook
Create Activity: ضع الاسم MainActivity الذي سيمثل الشاشة الرئيسية للتطبيق.
Minimum SDK: اقل اصدارة من النظام التي يمكن ان يعمل عليها التطبيق.
الان تم انشاء مشروع تطبيق Android.
وصف محتويات مجلد التطبيق

src: يحتوي Java source.
gen: يحتوي حزمة منشأة بصورة تلقائية بواسطة حزمة التطوير تحتوي R.java وهو ملف مرجعي للربط بين Java source و مصادر Android.
Android 2.1: مكتبة النظام.
assets: ملفات تحتجها في التطبيق لا ترغب في ان يمسها شيء مثل ملفات الصوت والخطوط.
bin: مجلد يجمع جميع المخرجات كحزمة التطبيق apk.
res: مجلد يحتوي على جميع مصادر Android.
res > drawable: مجلد يحتوي على الصور.PNG, JPEG, or GIF
res > menu: مجلد يحتوي ملفات XML لبناء القوائم.
res > layout: مجلد يحتوي الواجهات.
res > values: مجلد يحتوي القيم كالمسميات والرسائل يستفاد منه في جعل التطبيق يدعم اكثر من لغة.
AndroidManifest.xml: ملف اعداد التطبيق.
بداية
أولا: Model
يكتب بناءا على UML Class Diagram الذي يحتوي Class واحد اسمه Contact. سيكون تحت حزمة جديدة اسمها abdullah.android.addressbook.model
طريقة انشاء حزمة جديدة
طريقة انشاء Class جديد
Contact.java
كود:
package abdullah.android.addressbook.model;
public class Contact {
//contact id
private long id;
//contact first name
private String firstName;
//contact last name
private String lastName;
//contact phone no.
private String phoneNo;
//contact email
private String email;
//contact address
private String address;
public Contact() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
/**
* @param obj the object that you want to compare it with this object.<br/>
* @return if obj equals this object.
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contact other = (Contact) obj;
if (id != other.id)
return false;
return true;
}
}
ثانيا: قاعدة البيانات
نكتب class جديد من SQLiteOpenHelper اسمه MySQLiteHelper وسيكون المسؤول عن انشاء قاعدة البيانات
المزيد.
سيكون تحت حزمة abdullah.android.addressbook
طريقة انشاء Class جديد
MySQLiteHelper.java
كود:
package abdullah.android.addressbook;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper {
//Table name
public static final String TABLE_CONTACTS = "contact_table";
//Table columns
public static final String COLUMN_ID = "_id";
public static final String COLUMN_FIRST_NAME = "first_name";
public static final String COLUMN_LAST_NAME = "last_name";
public static final String COLUMN_PHONE_NO = "phone_no";
public static final String COLUMN_EMAIL = "email";
public static final String COLUMN_ADDRESS = "address";
//Database file name
private static final String DATABASE_NAME = "address_book.db";
//Database version
private static final int DATABASE_VERSION = 1;
// Database creation sql statement
private static final String DATABASE_CREATE = "create table "
+ TABLE_CONTACTS + "( " + COLUMN_ID
+ " integer primary key autoincrement, "
+ COLUMN_FIRST_NAME + " text not null, "
+ COLUMN_LAST_NAME + " text, "
+ COLUMN_PHONE_NO + " text, "
+ COLUMN_EMAIL + " text, "
+ COLUMN_ADDRESS + " text "
+ ");";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/** Called on first creation of the database. */
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
/** Called when the DATABASE_VERSION is changed to higher version */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
}
سيكون معتمدا على ERD الموجود في بداية الموضوع.
نكتب class اخر سيتعامل مع بيانات قاعدة البيانات كالاضافة والتعديل والحذف وجلب البيانات سيكون اسمه ContactDataSource تحت نفس الجزمة abdullah.android.addressbook
طريقة انشاء Class جديد
ContactDataSource.java
كود:
package abdullah.android.addressbook;
import java.util.ArrayList;
import java.util.List;
import abdullah.android.addressbook.model.Contact;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class ContactDataSource {
// SQLite Database object
private SQLiteDatabase database;
// Our SQLiteOpenHelper
private MySQLiteHelper dbHelper;
//Database columns
private String[] allColumns = { MySQLiteHelper.COLUMN_ID,
MySQLiteHelper.COLUMN_FIRST_NAME, MySQLiteHelper.COLUMN_LAST_NAME,
MySQLiteHelper.COLUMN_PHONE_NO, MySQLiteHelper.COLUMN_EMAIL,
MySQLiteHelper.COLUMN_ADDRESS};
public ContactDataSource(Context context){
dbHelper = new MySQLiteHelper(context);
}
/** Used to open connection with database. */
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
/** Used to close connection with database. */
public void close() {
dbHelper.close();
}
/** Add new Contact to Database. */
public Contact createContact(Contact contact) {
//Used to store data like : COLUMN_NAME , VALUE.
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FIRST_NAME, contact.getFirstName());
values.put(MySQLiteHelper.COLUMN_LAST_NAME, contact.getLastName());
values.put(MySQLiteHelper.COLUMN_PHONE_NO, contact.getPhoneNo());
values.put(MySQLiteHelper.COLUMN_EMAIL, contact.getEmail());
values.put(MySQLiteHelper.COLUMN_ADDRESS, contact.getAddress());
//Insert new contact and get the id of it.
long insertId = database.insert(MySQLiteHelper.TABLE_CONTACTS, null,
values);
//To show how to query (To get contact by it id).
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + insertId, null,
null, null, null);
//Move Cursor to the first row.
cursor.moveToFirst();
return cursorToContact(cursor);
}
/** Update Contact in Database. */
public Contact updateContact(Contact contact) {
//Used to store data like : COLUMN_NAME , VALUE.
ContentValues values = new ContentValues();
values.put(MySQLiteHelper.COLUMN_FIRST_NAME, contact.getFirstName());
values.put(MySQLiteHelper.COLUMN_LAST_NAME, contact.getLastName());
values.put(MySQLiteHelper.COLUMN_PHONE_NO, contact.getPhoneNo());
values.put(MySQLiteHelper.COLUMN_EMAIL, contact.getEmail());
values.put(MySQLiteHelper.COLUMN_ADDRESS, contact.getAddress());
database.update(MySQLiteHelper.TABLE_CONTACTS, values, MySQLiteHelper.COLUMN_ID + "=" + contact.getId(), null);
//To show how to query (To get contact by it id).
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + contact.getId(), null,
null, null, null);
//Move Cursor to the first row.
cursor.moveToFirst();
return cursorToContact(cursor);
}
/** Delete Contact from Database. */
public void deleteContact(Contact contact) {
System.out.println("Contact deleted with id: " + contact.getId());
//Delete contact by it id.
database.delete(MySQLiteHelper.TABLE_CONTACTS, MySQLiteHelper.COLUMN_ID
+ " = " + contact.getId(), null);
}
/** Get all Contacts from Database. */
public List<Contact> getAllContacts() {
//Used to store all contacts.
List<Contact> comments = new ArrayList<Contact>();
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,
allColumns, null, null, null, null, null);
//Move Cursor to the first row.
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
Contact contact = cursorToContact(cursor);
comments.add(contact);
//Move Cursor to the next row.
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return comments;
}
/** Used to get contact by it id. */
public Contact getContact(long id){
Cursor cursor = database.query(MySQLiteHelper.TABLE_CONTACTS,
allColumns, MySQLiteHelper.COLUMN_ID + " = " + id, null,
null, null, null);
cursor.moveToFirst();
return cursorToContact(cursor);
}
/** Used to get contact data from Cursor to Contact Object. */
private Contact cursorToContact(Cursor cursor) {
Contact contact = new Contact();
contact.setId(cursor.getLong(0));
contact.setFirstName(cursor.getString(1));
contact.setLastName(cursor.getString(2));
contact.setPhoneNo(cursor.getString(3));
contact.setEmail(cursor.getString(4));
contact.setAddress(cursor.getString(5));
return contact;
}
}
ثالثا: الواجهات ستكون تحت res>layout
بناءا على الشكل مقترح في بداية الموضوع سيكون لدينا واجهتين هما:
الواجهة الرئيسية
ستكون واجهة تعرض جميع الاسماء.
لذلك سنستخدم ListView ستعرض جميع الاسماء الموجودة في قاعدة بيانات التطبيق.
سنسميها main.xml. ملاحظة: هذا الملف قد يكون موجود مسبقا لذلك يمكن ان نقوم بتعديله.
طريقة انشاء ملف Android XML (واجهة) جديد
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:orientation="vertical" >
<!-- Used to view list of all contacts -->
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
بما اننا سنتخدم ListView التي ستحتوي مجموعة من View سنحتاج واجهة لهذه الـ View.
سنعرض فيها الاسم الكامل ورقم الهاتف وصورة.
طريقة انشاء ملف Android XML (واجهة) جديد
contact_list_item.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:paddingTop="4dp"
android:paddingRight="8dp"
android:paddingBottom="4dp"
android:paddingLeft="8dp">
<!-- Left side of the view contains Contact Full Name and Contact Phone No. -->
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_weight="1">
<TextView android:id="@+id/contact_name_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@android:style/TextAppearance.Large"
android:text="Name"/>
<TextView android:id="@+id/contact_phone_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="@android:style/TextAppearance.Small"
android:text="Phone No."/>
</LinearLayout>
<!-- Right side of the view contains Image -->
<ImageView android:layout_width="48dp" android:layout_height="48dp"
android:src="@drawable/p_team_logo"/>
</LinearLayout>
واجهة التعديل
ستحتوي مربعات نص للاسم ورقم الهاتف والبريد الالكتروني والعنوان وزي حفظ والغاء.
طريقة انشاء ملف Android XML (واجهة) جديد
edit_contact.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:orientation="vertical">
<!-- ScrollView contains EditText because if the phone screen is small the view well have scroll bar. -->
<ScrollView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/p_team_logo"/>
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- EditText (TextBox) for First Name -->
<EditText android:id="@+id/contact_first_name_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:hint="First Name"/>
<!-- EditText (TextBox) for Last Name -->
<EditText android:id="@+id/contact_last_name_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:hint="Last Name"/>
</LinearLayout>
<!-- EditText (TextBox) for Phone No. -->
<EditText android:id="@+id/contact_phone_no_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="phone"
android:hint="Phone No."/>
<!-- EditText (TextBox) for Email -->
<EditText android:id="@+id/contact_email_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:inputType="textEmailAddress"
android:hint="Email"/>
<!-- EditText (TextBox) for Address -->
<EditText android:id="@+id/contact_address_txt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:maxLines="4"
android:inputType="textMultiLine"
android:hint="Address"/>
</LinearLayout>
</ScrollView>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Discard Button -->
<Button android:id="@+id/discard_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Discard"/>
<!-- Save Button -->
<Button android:id="@+id/save_btn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Save"/>
</LinearLayout>
</LinearLayout>
رابعا: القوائم Menus ستكون تحت res>menu
سيكون لكل واجهة قائمة كالتالي:
الواجهة الرئيسية
ستحتوي ثلاثة عناصر هي: الاضافة (لاضافة اسم جديد) و البحث (للبحث عن اسم) الاعدادات.
طريقة انشاء ملف Android XML (قائمة) جديد
main_menu.xml
كود:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/add_contact_option" android:title="Add"/>
<item android:id="@+id/search_option" android:title="Search"/>
<item android:id="@+id/settings_option" android:title="Settings"/>
</menu>
واجهة التعديل
ستحتوي عنصر واحد هو الحذف.
طريقة انشاء ملف Android XML (قائمة) جديد
edit_menu.xml
كود:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/delete_contact_option" android:title="Delete"/>
</menu>
خامسا: صور ستكون تحت res>drawable
انا استخدم صورة واحدة p_team_logo.png

استخدمتها في الواجهات السابقة
ملاحظة: يلاحظ انه لا يوجد مجلد اسمه drawable بل يوجد مجلدات آخرى كالتالي:
drawable-hdpi: للشاشات عالية الدقة كـ SAMSUNG Galaxy (S, SII, R) واغلب الاجهزة.
drawable-mdpi: للشاشات متوسطة الدقة كـ HTC (Dream, Magic Hero) وبعض الاجهزة.
drawable-ldpi: للشاشات منخفظة الدقة كـ HTC Tatto و SAMSUNG Galaxy Ace.
المرجع الكامل
كما ان نفس الفكرة تنطبق على الواجهات layout.
ملاحظة: طريقة اضافة الصور هي النسخ واللصق.
سادسا: Activities جمع Activity
لكل واجهة Activity.
المرجع
الواجهة الرئيسية
سيكون اسمه MainActivity سيعرض فيه قائمة من الاسماء سنستخدم الواجهة main.xml.
لاننا سنسخدم ListView في main.xml سنختار ListActivity بدلا من Activity لتخصصه في القوائم.
طريقة انشاء Class جديد
MainActivity.java
كود:
package abdullah.android.addressbook;
import java.util.ArrayList;
import java.util.List;
import abdullah.android.addressbook.model.Contact;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
//Our DataSource to work with database.
private ContactDataSource dataSource;
//Used to store all contacts to be used in ListView adapter.
private List<Contact> contacts = new ArrayList<Contact>();
//To be used as an adapter with ListView.
private ContactAdapter adapter;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set layout main.xml
setContentView(R.layout.main);
//Create object from ContactDataSource.
dataSource = new ContactDataSource(this);
// Use the ContactAdapter to show the elements in a ListView.
adapter = new ContactAdapter(this);
setListAdapter(adapter);
//ListView is the ListView with android:id="@android:id/list" in the layout (main.xml). to get it you can call getListView()
//Set OnItemClickListener triggers when user click any item (Contact) in the list.
getListView().setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long id) {
// Open EditActivity to edit the clicked Contact.
Intent editIntent = new Intent(MainActivity.this, EditActivity.class);
//Put the Contact id
editIntent.putExtra("id", id);
//Start EditActivity to edit the clicked Contact.
startActivity(editIntent);
}
});
}
/** Call after onCreate method. */
@Override
protected void onResume() {
super.onResume();
//Open database connection.
dataSource.open();
//Get all contacts.
contacts = dataSource.getAllContacts();
//Notify adapter that there is a change in contacts list.
adapter.notifyDataSetChanged();
}
/** Call after close activity */
@Override
protected void onStop() {
super.onStop();
//Close dataSource
dataSource.close();
}
/** Called when click Menu button. */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
//Generate menu from main_menu.xml menu.
inflater.inflate(R.menu.main_menu, menu);
return true;
}
/** Called when select option from menu. */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Check witch option selected.
switch (item.getItemId()) {
case R.id.add_contact_option:
//Start EditActivity.
startActivity(new Intent(this, EditActivity.class));
return true;
case R.id.search_option:
Toast.makeText(this, "Search Option clicked.", Toast.LENGTH_SHORT);
return true;
case R.id.settings_option:
Toast.makeText(this, "Settings Option clicked.", Toast.LENGTH_SHORT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Adapter to handle ListView items (Contacts).
private class ContactAdapter extends BaseAdapter{
//Used to create view.
private LayoutInflater mInflater;
public ContactAdapter(Context context){
mInflater = LayoutInflater.from(context);
}
/** Get the adapter items (Contacts) count */
@Override
public int getCount() {
return contacts.size();
}
/** Get item (Contact) by position */
@Override
public Object getItem(int position) {
return contacts.get(position);
}
/** Get item (Contact) id by position */
@Override
public long getItemId(int position) {
return contacts.get(position).getId();
}
/** Get item (Contact) view by position */
@Override
public View getView(int position, View convertView, ViewGroup parent) {
//Create view from contact_list_item.xml layout.
if(convertView == null)
convertView = mInflater.inflate(R.layout.contact_list_item, null);
//Get TextView by it id (android:id)
TextView contactNameTxt = (TextView)convertView.findViewById(R.id.contact_name_txt);
TextView contactPhoneTxt = (TextView)convertView.findViewById(R.id.contact_phone_txt);
//
Contact current = (Contact)getItem(position);
//Set Contact name.
contactNameTxt.setText(current.getFirstName() + " " + current.getLastName());
//Set Contact Phone No.
contactPhoneTxt.setText(current.getPhoneNo());
return convertView;
}
}
}
واجهة التعديل
الواجهة التي تمكننا من اضافة وتعديل وحذف الاسماء.
طريقة انشاء Class جديد
EditActivity.java
كود:
package abdullah.android.addressbook;
import abdullah.android.addressbook.model.Contact;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class EditActivity extends Activity {
//Our DataSource to work with database.
private ContactDataSource dataSource;
//Used to store Contact data.
private Contact contact;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set layout edit_contact.xml
setContentView(R.layout.edit_contact);
//Create object from ContactDataSource.
dataSource = new ContactDataSource(this);
//Open database connection.
dataSource.open();
//When any other Activity sends any data we can found it in this object.
Bundle b = this.getIntent().getExtras();
if(b != null){
//Get the Contact by the sent id.
contact = dataSource.getContact(b.getLong("id"));
}
//Get EditText (Textbox) by android:id
final EditText firstNameTxt = (EditText) findViewById(R.id.contact_first_name_txt);
final EditText lastNameTxt = (EditText) findViewById(R.id.contact_last_name_txt);
final EditText phoneNoTxt = (EditText) findViewById(R.id.contact_phone_no_txt);
final EditText emailTxt = (EditText) findViewById(R.id.contact_email_txt);
final EditText addressTxt = (EditText) findViewById(R.id.contact_address_txt);
//Fill contact data in the EditText (Textbox).
if(contact != null){
firstNameTxt.setText(contact.getFirstName());
lastNameTxt.setText(contact.getLastName());
phoneNoTxt.setText(contact.getPhoneNo());
emailTxt.setText(contact.getEmail());
addressTxt.setText(contact.getAddress());
}
//Get buttons
final Button discardBtn = (Button) findViewById(R.id.discard_btn);
final Button saveBtn = (Button) findViewById(R.id.save_btn);
//Set OnClickListener for Save button.
saveBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(contact == null)
contact = new Contact();
contact.setFirstName(firstNameTxt.getText().toString());
contact.setLastName(lastNameTxt.getText().toString());
contact.setPhoneNo(phoneNoTxt.getText().toString());
contact.setEmail(emailTxt.getText().toString());
contact.setAddress(addressTxt.getText().toString());
if(contact.getId() == 0){
contact = dataSource.createContact(contact);
Toast.makeText(EditActivity.this, "New contact added.", Toast.LENGTH_LONG).show();
}else{
contact = dataSource.updateContact(contact);
Toast.makeText(EditActivity.this, "Contact updated.", Toast.LENGTH_LONG).show();
}
finish();
}
});
//Set OnClickListener for Discard button.
discardBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
finish();
}
});
}
/** Call after close activity */
@Override
protected void onStop() {
super.onStop();
//Close dataSource
dataSource.close();
}
/** Called when click Menu button. */
@Override
public boolean onCreateOptionsMenu(Menu menu) {
//If contact is null this means we can't delete not saved to database Contact.
if(contact != null){
MenuInflater inflater = getMenuInflater();
//Generate menu from edit_menu.xml menu.
inflater.inflate(R.menu.edit_menu, menu);
return true;
}else
return super.onCreateOptionsMenu(menu);
}
/** Called when select option from menu. */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//Check witch option selected.
switch (item.getItemId()) {
case R.id.delete_contact_option:
//Delete current Contact
dataSource.deleteContact(contact);
Toast.makeText(EditActivity.this, "Contact deleted.", Toast.LENGTH_LONG).show();
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
سابعا: ملف AndroidManifest.xml
ملف يحتوي اعدادات التطبيق
نقوم بتسجيل Activity اللتي كتبناها كـ MainActivity و EditActivity
AndroidManifest.xml
كود:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="abdullah.android.addressbook"
android:versionCode="1"
android:versionName="1.0" >
<application android:icon="@drawable/p_team_logo" android:label="@string/app_name">
<!-- To use any Activity class we need to register it here. -->
<!-- MainActivity -->
<activity android:name=".MainActivity" android:label="@string/app_name" >
<intent-filter>
<!-- This means this is the main activity -->
<action android:name="android.intent.action.MAIN" />
<!-- This means this activity well have a shortcut -->
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- EditActivity -->
<activity android:name=".EditActivity"/>
</application>
<!-- This means this app well work with Android 2.1 (7) and later -->
<uses-sdk android:minSdkVersion="7" />
</manifest>
ثامنا: التجربة والاختبار Debug
لتجربة التطبيق نحتاج جهاز به نظام Android مع تفعيل خاصية USB Debugging. او Android Emulator.
جهاز Android
في حالة وجود جهاز Android يجب تفعيل الخاصيات التالية:
Unknown sources
Android 3.2 او اقدم
Settings > Applications
Android 4.0 او احدث
Settings > Security
USB Debugging
لتفعيل الخاصية:
Android 3.2 او اقدم
Settings > Applications > Development
Android 4.0 او احدث
Settings > Developer options
Android Emulator
شرح طريقة العمل مع Android Emulator
هنا.
المفضلات