Click here to Skip to main content
15,860,972 members
Articles / Mobile Apps / Xamarin

Xamarin Android App Using SQLite and Custom ListView

Rate me:
Please Sign up or sign in to vote.
4.79/5 (20 votes)
6 Apr 2016CPOL5 min read 59.8K   1.6K   35   15
This tutorial will explain how to develop android app with Xamarin tool provided by visual studio. This post will walk you through creating a small android app related to AddressBook.

Introduction

     After reading this tutorial you will be able to know:
  • How to create android project in visual studio and setting up JDK and Android SDK location in visual studio IDE. How to create style and apply it on our layout components
  • How to create SQLite database and perform CRUD operation
  • How to create custom ListView and some operation with it
  • How to pass values between activities using intents
For your good understanding, I am creating app for Address Book which will have functionality of displaying contact lists, search contacts according to contact name, create new contacts, edit existing contact information, and delete contacts. Following snapshots shows how the app we are creating will look like
 
Snapshot 1: Contact List screen

 

Snapshot 2: Form to add new contact or edit existing contact

 

Snapshot 3: Delete contact

 
Setup JDK and Android SDK Location

Before creating your first app, firstly you just need to make sure that Android Setting of your Xamarin is correct or not. You can check it from Tools->Options->Xamarin->Android Setting on Microsoft Visual Studio start page. Moreover, you can change the location of JDK and Android SDK if necessary.

 
Now create a new Xamarin project, you can create blank project by choosing “Blank App” option on New Project window. A default project containing Assets and Resources folder is ready. Moreover, initially you can change basic application properties such as “Android Version to Compile”, “Minimum android target version”, “and Default target version” just by right clicking project under solution explorer and properties.
 

SQLite Database for Address book

Add a new class AddressBookDbSelper.cs and extend it from SQLiteOpenHelper base class. In this class I would write code to create a table AddressBook on OnCreate method then write some methods to select, insert, update, and delete contacts.
  • GetAllContacts(): Retrive all contacts available in the database.
  • GetContactsBySearchName(string nameToSearch): Read contacts according to passed search parameter nameToSearch.  
  • AddNewContact(AddressBook contactinfo): Insert new contact information.
  • UpdateContact(AddressBook contitem): Update existing contact based on Id property of the class AddressBook.
  • DeleteContact(string  contactId): Delete existing contact according to contact Id.

 

C#
  public class AddressBookDbHelper: SQLiteOpenHelper
    {
        private const string APP_DATABASENAME = "Student.db3";
        private const int APP_DATABASE_VERSION = 1;

        public AddressBookDbHelper(Context ctx):
            base(ctx, APP_DATABASENAME, null, APP_DATABASE_VERSION)
        {

        }

        public override void OnCreate(SQLiteDatabase db)
        {
            db.ExecSQL(@"CREATE TABLE IF NOT EXISTS AddressBook(
                            Id INTEGER PRIMARY KEY AUTOINCREMENT,
                            FullName TEXT NOT NULL,
                            Mobile  TEXT NOT NULL,
                            Email   TEXT NULL,
                            Details TEXT)");

            db.ExecSQL("Insert into AddressBook(FullName,Mobile,Email,Details)VALUES('Sharad Chandra Pyakurel','9851162459','sharad.pyakurel@gmail.com','this is details')");
            
            db.ExecSQL("Insert into AddressBook(FullName,Mobile,Email,Details)VALUES('Gopal Prasad','9841258963','gopal.pyakurel@gmail.com','this is details')");

        }

        public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
        {
            db.ExecSQL("DROP TABLE IF EXISTS AddressBook");
            OnCreate(db);
        }

        //Retrive All Contact Details
        public IList<AddressBook> GetAllContacts()
        {

            SQLiteDatabase db = this.ReadableDatabase;

           ICursor c =  db.Query("AddressBook", new string[] { "Id", "FullName", "Mobile", "Email", "Details" }, null, null, null, null, null);

            var contacts = new List<AddressBook>();

            while (c.MoveToNext())
            {
                contacts.Add(new AddressBook
                        {
                            Id = c.GetInt(0),
                            FullName = c.GetString(1),
                            Mobile = c.GetString(2),
                            Email = c.GetString(3),
                            Details = c.GetString(4) }); 
            }

            c.Close();
            db.Close();

            return contacts;
        }


        //Retrive All Contact Details
        public IList<AddressBook> GetContactsBySearchName(string nameToSearch)
        {

            SQLiteDatabase db = this.ReadableDatabase;

            ICursor c = db.Query("AddressBook", new string[] { "Id", "FullName", "Mobile", "Email", "Details" }, "upper(FullName) LIKE ?", new string[] {"%"+ nameToSearch.ToUpper() +"%"}, null, null, null, null);

            var contacts = new List<AddressBook>();

            while (c.MoveToNext())
            {
                contacts.Add(new AddressBook
                {
                    Id = c.GetInt(0),
                    FullName = c.GetString(1),
                    Mobile = c.GetString(2),
                    Email = c.GetString(3),
                    Details = c.GetString(4)
                });
            }

            c.Close();
            db.Close();

            return contacts;
        }

        //Add New Contact
        public void AddNewContact(AddressBook contactinfo)
        {
            SQLiteDatabase db = this.WritableDatabase;
            ContentValues vals = new ContentValues();
            vals.Put("FullName", contactinfo.FullName);
            vals.Put("Mobile", contactinfo.Mobile);
            vals.Put("Email", contactinfo.Email);
            vals.Put("Details", contactinfo.Details);
            db.Insert("AddressBook", null, vals);
        }

        //Get contact details by contact Id
        public ICursor getContactById(int id)
        {
            SQLiteDatabase db = this.ReadableDatabase;
            ICursor res = db.RawQuery("select * from AddressBook where Id=" + id + "", null);
            return res;
        }

        //Update Existing contact
        public void UpdateContact(AddressBook contitem)
        {
            if (contitem == null)
            {
                return;
            }

            //Obtain writable database
            SQLiteDatabase db = this.WritableDatabase;

            //Prepare content values
            ContentValues vals = new ContentValues();
            vals.Put("FullName", contitem.FullName);
            vals.Put("Mobile", contitem.Mobile);
            vals.Put("Email", contitem.Email);
            vals.Put("Details", contitem.Details);


            ICursor cursor = db.Query("AddressBook",
                    new String[] {"Id", "FullName", "Mobile", "Email", "Details" }, "Id=?", new string[] { contitem.Id.ToString() }, null, null, null, null);

            if (cursor != null)
            {
                if (cursor.MoveToFirst())
                {
                    // update the row
                    db.Update("AddressBook", vals, "Id=?", new String[] { cursor.GetString(0) });
                }

                cursor.Close();
            }

        }


        //Delete Existing contact
        public void DeleteContact(string  contactId)
        {
            if (contactId == null)
            {
                return;
            }

            //Obtain writable database
            SQLiteDatabase db = this.WritableDatabase;

            ICursor cursor = db.Query("AddressBook",
                    new String[] { "Id", "FullName", "Mobile", "Email", "Details" }, "Id=?", new string[] { contactId }, null, null, null, null);

            if (cursor != null)
            {
                if (cursor.MoveToFirst())
                {
                    // update the row
                    db.Delete("AddressBook", "Id=?", new String[] { cursor.GetString(0) });
                }

                cursor.Close();
            }

        }
        


    }

The class AddressBook contains following properties which is matched with the columns in the table AddressBook

C#
   public class AddressBook
    {
        public int Id { get; set; }
        public string FullName { get; set; }
        public string Mobile { get; set; }
        public string Email { get; set; }
        public string Details { get; set; }

        public static explicit operator AddressBook(Java.Lang.Object v)
        {
            throw new NotImplementedException();
        }
    }

 

Creating ListView and custom base adapter for ListView

The contact list will be populated in the list view. At the top of ListView two buttons for “Add new contact” and “Search”, and a EditText to input search parameters has added. descendantFocusability="beforeDescendants ensures This view will get focus before any of its descendants.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:paddingBottom="1dp"
    android:paddingLeft="1dp"
    android:paddingRight="1dp"
    android:paddingTop="0dp">
    <TableLayout
        android:id="@+id/tableLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TableRow>
            <Button
                android:id="@+id/contactList_btnAdd"
                style="@style/button_style"
                android:layout_weight="1"
                android:text="Add New Contact" />
        </TableRow>
        <TableRow>
            <EditText
                android:id="@+id/contactList_txtSearch"
                style="@style/input_style"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:hint="Search" />
            <Button
                android:id="@+id/contactList_btnSearch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="#0f87ff"
                android:layout_marginRight="1dp"
                android:paddingTop="9dp"
                android:paddingBottom="9dp"
                android:text="Search"
                android:textAlignment="center"
                android:textAllCaps="false"
                android:minHeight="0dp"
                android:textColor="#fff"
                android:textSize="15sp" />
        </TableRow>
    </TableLayout>
    <ListView
        android:id="@+id/contactList_listView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tableLayout"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:clickable="true"
        android:divider="#b5b5b5"
        android:dividerHeight="1dp"
        android:listSelector="@drawable/list_selector" />
</RelativeLayout>
This id will be used to initialize this from activity cs file. We need to create a separate xml file for items in ListView row. The list row layout will define the layout for list row item. This layout will be used by the custom list adapter.
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/list_selector"
    android:orientation="vertical"
    android:padding="2dp">

    <TableLayout
        android:layout_width="fill_parent"
        android:padding="3dp"
        android:layout_height="wrap_content">

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Name: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_fullName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Full Name"
                android:textColor="#0000dd"
                android:textSize="15dp"
                android:textStyle="bold" />
        </TableRow>


        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Mobile: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_mobile"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Mobile"
                android:textColor="#0000dd"
                android:textSize="15dip"
                android:textStyle="bold" />

        </TableRow>

        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Email: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_email"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="Email"
                android:textColor="#0000dd"
                android:textSize="15dp" />
        </TableRow>


        <TableRow
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="2dp"
                android:text="Description: "
                android:textColor="#000" />

            <TextView
                android:id="@+id/lr_descriptin"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="10dp"
                android:layout_weight="1"
                android:text="description"
                android:textColor="#0000dd"
                android:textSize="15dp" />
        </TableRow>




    </TableLayout>

  <ImageView 
    android:id="@+id/lr_deleteBtn"
    android:layout_width="50dip" 
    android:layout_height="100dip"
    android:src="@drawable/delete"
      android:layout_alignParentRight="true"
          android:clickable="true"
    />


</RelativeLayout>
Since we are creating a custom ListView, we now need to create a custom adapter. This custom adapter will extend a generic base adapter AddressBook. This adapter’s constructor accepts an Activty as context and a List of type AddressBook. An adapter takes list of data objects as input, and each object in the list is mapped to a list row. Adapter also inflates the layout to be rendered for each row items. It is the most important and tricky part on creating a custom ListView. 
C#
[Activity(Label = "ContactListBaseAdapter")]
public partial class ContactListBaseAdapter : BaseAdapter<AddressBook>
{
    IList<AddressBook> contactListArrayList;
    private LayoutInflater mInflater;
    private Context activity;
    public ContactListBaseAdapter(Context context,
                                            IList<AddressBook> results)
    {
        this.activity = context;
        contactListArrayList = results;
        mInflater = (LayoutInflater)activity.GetSystemService(Context.LayoutInflaterService);
    }

    public override int Count
    {
        get { return contactListArrayList.Count; }
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override AddressBook this[int position]
    {
        get { return contactListArrayList[position]; }
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        ImageView btnDelete;
        ContactsViewHolder holder = null;
        if (convertView == null)
        {
            convertView = mInflater.Inflate(Resource.Layout.list_row_contact_list, null);
            holder = new ContactsViewHolder();

            holder.txtFullName = convertView.FindViewById<TextView>(Resource.Id.lr_fullName);
            holder.txtMobile = convertView.FindViewById<TextView>(Resource.Id.lr_mobile);
            holder.txtEmail = convertView.FindViewById<TextView>(Resource.Id.lr_email);
            holder.txtDescription = convertView.FindViewById<TextView>(Resource.Id.lr_descriptin);
            btnDelete = convertView.FindViewById<ImageView>(Resource.Id.lr_deleteBtn);

            btnDelete.Click += (object sender, EventArgs e) =>
            {

                AlertDialog.Builder builder = new AlertDialog.Builder(activity);
                AlertDialog confirm = builder.Create();
                confirm.SetTitle("Confirm Delete");
                confirm.SetMessage("Are you sure delete?");
                confirm.SetButton("OK", (s, ev) =>
                {
                    var poldel = (int)((sender as ImageView).Tag);

                    string id = contactListArrayList[poldel].Id.ToString();
                    string fname = contactListArrayList[poldel].FullName;

                    contactListArrayList.RemoveAt(poldel);

                    DeleteSelectedContact(id);
                    NotifyDataSetChanged();

                    Toast.MakeText(activity, "Contact Deeletd Successfully", ToastLength.Short).Show();
                });
                confirm.SetButton2("Cancel", (s, ev) =>
                {

                });

                confirm.Show();
            };

            convertView.Tag = holder;
            btnDelete.Tag = position;
        }
        else
        {
            btnDelete = convertView.FindViewById<ImageView>(Resource.Id.lr_deleteBtn);
            holder = convertView.Tag as ContactsViewHolder;
            btnDelete.Tag = position;
        }

        holder.txtFullName.Text = contactListArrayList[position].FullName.ToString();
        holder.txtMobile.Text = contactListArrayList[position].Mobile;
        holder.txtEmail.Text = contactListArrayList[position].Email;
        holder.txtDescription.Text = contactListArrayList[position].Details;

        if (position % 2 == 0)
        {
            convertView.SetBackgroundResource(Resource.Drawable.list_selector);
        }
        else
        {
            convertView.SetBackgroundResource(Resource.Drawable.list_selector_alternate);
        }

        return convertView;
    }

    public IList<AddressBook> GetAllData()
    {
        return contactListArrayList;
    }

    public class ContactsViewHolder : Java.Lang.Object
    {
        public TextView txtFullName { get; set; }
        public TextView txtMobile { get; set; }
        public TextView txtEmail { get; set; }
        public TextView txtDescription { get; set; }
    }

    private void DeleteSelectedContact(string contactId)
    {
        AddressBookDbHelper _db = new AddressBookDbHelper(activity);
        _db.DeleteContact(contactId);
    }

}
The ContactViewHolder enables you to access each list item view without the need for the look up. It represents items in the list row. You must override the Count, GetItemId and GetView method in your BaseAdapter class implementation. The Count method indicates the total number of rows in the list, GetItemId represent a unique id for reach item in the list. GetView inflates layout for each list row and render on the screen. To implement delete functionality on list view row, code to manage click event of delete button is placed in GetView method. The tag of the delete button will determine the position of row to be deleted. The position of row is divided by 2 to find alternate row in the listview and apply style accordingly.

Setting custom Adapter to ListView

Once our custom adapter is ready, we need to instantiate this adapter to set to ListView.

C#
[Activity(Label = "Contact List", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
    Button btnAdd, btnSearch;
    EditText txtSearch;
    ListView lv;
    IList<AddressBook> listItsms = null;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        btnAdd = FindViewById<Button>(Resource.Id.contactList_btnAdd);
        btnSearch = FindViewById<Button>(Resource.Id.contactList_btnSearch);
        txtSearch = FindViewById<EditText>(Resource.Id.contactList_txtSearch);
        lv = FindViewById<ListView>(Resource.Id.contactList_listView);

        btnAdd.Click += delegate
        {
            var activityAddEdit = new Intent(this, typeof(AddEditAddressBookActivity));
            StartActivity(activityAddEdit);

        };

        btnSearch.Click += delegate
          {
              LoadContactsInList();
          };

        LoadContactsInList();

    }

    private void LoadContactsInList()
    {
        AddressBookDbHelper dbVals = new AddressBookDbHelper(this);
        if (txtSearch.Text.Trim().Length < 1)
        {
            listItsms = dbVals.GetAllContacts();
        }
        else {

            listItsms = dbVals.GetContactsBySearchName(txtSearch.Text.Trim());
        }

        lv.Adapter = new ContactListBaseAdapter(this, listItsms);

        lv.ItemLongClick += lv_ItemLongClick;
    }

    private void lv_ItemLongClick(object sender, AdapterView.ItemLongClickEventArgs e)
    {
        AddressBook o = listItsms[e.Position];

        var activityAddEdit = new Intent(this, typeof(AddEditAddressBookActivity));
        activityAddEdit.PutExtra("ContactId", o.Id.ToString());
        activityAddEdit.PutExtra("ContactName", o.FullName);
        StartActivity(activityAddEdit);
    }

}

We have created lv_ItemLongClick call back to handle ListView long press event. The selected contact will open in new window for edit with existing information filled in when we long press the item in ListView. The value indicating edit mode is passed using intent PutExtra method.

 

Add Or Edit contacts

The design layout related to adding new contact or editing existing contact is written in the following code block. The design view of this layout is shown just below the following code block.

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:scrollbars="none">
        <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content">
            <TableRow
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Contact Id " />
                <EditText
                    android:id="@+id/addEdit_ContactId"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:editable="false"
                    android:hint="Contact Id" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Full Name " />
                <EditText
                    android:id="@+id/addEdit_FullName"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_ContactId"
                    android:layout_weight="1"
                    android:hint="Full Name" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Mobile" />
                <EditText
                    android:id="@+id/addEdit_Mobile"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_FullName"
                    android:layout_weight="1"
                    android:hint="Mobile" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Email" />
                <EditText
                    android:id="@+id/addEdit_Email"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_Mobile"
                    android:layout_weight="1"
                    android:hint="Email" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="Description" />
                <EditText
                    android:id="@+id/addEdit_Description"
                    style="@style/input_style"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_below="@+id/addEdit_Email"
                    android:layout_weight="1"
                    android:gravity="top|left"
                    android:hint="Description"
                    android:inputType="textMultiLine"
                    android:lines="4"
                    android:scrollHorizontally="false"
                    android:scrollbars="vertical" />
            </TableRow>
            <TableRow
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=" " />
                <Button
                    android:id="@+id/addEdit_btnSave"
                    style="@style/button_style"
                    android:layout_weight="1"
                    android:text=" Save " />
            </TableRow>
        </TableLayout>
    </ScrollView>
</RelativeLayout>

 

It is often good idea to apply some visual style to various controls such as EditText, Button, or even the whole form. Generally some basic style can be applied using resource xml or image file that we have added in drawable. But we can create our separate style file mentioning appropriate styles such as size, color, margin, background, and etc in the form of a xml file. The xml code for style.xml which is used to apply style to controls is following:

XML
<resources>

  <style name="input_style">
    <item name="android:background">@drawable/input_shape</item>
    <item name="android:layout_marginTop">1dp</item>
    <item name="android:layout_marginRight">10dp</item>
    <item name="android:layout_marginBottom">7dp</item>
    <item name="android:paddingLeft">8dp</item>
    <item name="android:paddingTop">9dp</item>
    <item name="android:paddingBottom">9dp</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#000</item>
  </style>

  <style name="button_style">
    <item name="android:background">@drawable/button_shape</item>
    <item name="android:layout_width">match_parent</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:layout_margin">1dp</item>
    <item name="android:paddingLeft">5dp</item>
    <item name="android:paddingRight">5dp</item>
    <item name="android:paddingTop">9dp</item>
    <item name="android:paddingBottom">9dp</item>
    <item name="android:textSize">16sp</item>
    <item name="android:textColor">#fff</item>
    <item name="android:textAllCaps">false</item>
    <item name="android:minHeight">35dp</item>
  </style>
</resources>

The value received by Intent.GetStringExtra("ContactId") ?? string.Empty will determine the save mode of the contact. If we get positive Intent.GetStringExtra value then existing contact information of the particular Id will be loaded by LoadDataForEdit(string contactId) method thereby indicating edit mode. If the value is empty the activity will open in new entry mode.

C#
    [Activity(Label = "Add/Edit Contacts")]
    public class AddEditAddressBookActivity : Activity
    {
        EditText txtId, txtFullName, txtMobile, txtEmail, txtDescription;
        Button btnSave;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.AddEditContacts);

            txtId = FindViewById<EditText>(Resource.Id.addEdit_ContactId);
            txtFullName = FindViewById<EditText>(Resource.Id.addEdit_FullName);
            txtMobile = FindViewById<EditText>(Resource.Id.addEdit_Mobile);
            txtEmail = FindViewById<EditText>(Resource.Id.addEdit_Email);
            txtDescription = FindViewById<EditText>(Resource.Id.addEdit_Description);
            btnSave = FindViewById<Button>(Resource.Id.addEdit_btnSave);

            btnSave.Click += buttonSave_Click;

            string editId = Intent.GetStringExtra("ContactId") ?? string.Empty;

            if (editId.Trim().Length > 0)
            {
                txtId.Text = editId;
                LoadDataForEdit(editId);
            }
        }

        private void LoadDataForEdit(string contactId)
        {
            AddressBookDbHelper db = new AddressBookDbHelper(this);
            ICursor cData = db.getContactById(int.Parse(contactId));
            if (cData.MoveToFirst())
            {
                txtFullName.Text = cData.GetString(cData.GetColumnIndex("FullName"));
                txtMobile.Text = cData.GetString(cData.GetColumnIndex("Mobile"));
                txtEmail.Text = cData.GetString(cData.GetColumnIndex("Email"));
                txtDescription.Text = cData.GetString(cData.GetColumnIndex("Details"));
            }
        }

        void buttonSave_Click(object sender, EventArgs e)
        {
            AddressBookDbHelper db = new AddressBookDbHelper(this);
            if (txtFullName.Text.Trim().Length < 1)
            {
                Toast.MakeText(this, "Enter Full Name.", ToastLength.Short).Show();
                return;
            }

            if (txtMobile.Text.Trim().Length < 1)
            {
                Toast.MakeText(this, "Enter Mobile Number.", ToastLength.Short).Show();
                return;
            }

            if (txtEmail.Text.Trim().Length > 0)
            {
                string EmailPattern = @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
                if (!Regex.IsMatch(txtEmail.Text, EmailPattern, RegexOptions.IgnoreCase))
                {
                    Toast.MakeText(this, "Invalid email address.", ToastLength.Short).Show();
                    return;
                }
            }

            AddressBook ab = new AddressBook();

            if (txtId.Text.Trim().Length > 0)
            {
                ab.Id = int.Parse(txtId.Text);
            }
            ab.FullName = txtFullName.Text;
            ab.Mobile = txtMobile.Text;
            ab.Email = txtEmail.Text;
            ab.Details = txtDescription.Text;

            try
            {

                if (txtId.Text.Trim().Length > 0)
                {
                    db.UpdateContact(ab);
                    Toast.MakeText(this, "Contact Updated Successfully.", ToastLength.Short).Show();
                }
                else
                { 
                    db.AddNewContact(ab);
                    Toast.MakeText(this, "New Contact Created Successfully.", ToastLength.Short).Show();
                }

                Finish();

                //Go to main activity after save/edit
                var mainActivity = new Intent(this, typeof(MainActivity));
                StartActivity(mainActivity);

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
          
        }
    }

 

Please visit my youtube channel: https://www.youtube.com/channel/UCYESe2tTh9G6temYeaPNwwA

I will be posting some artical in my google blog: http://sharadpyakurel.blogspot.com

 

 

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NLIC
Nepal Nepal
I am in profession of an enterprise software development. I have good knowledge in object oriented programming, windows programming, enterprise web application development , mobile app development, and database designing and programming.

Comments and Discussions

 
QuestionMuhammad Fahim Pin
Member 1359179419-Jan-18 7:06
Member 1359179419-Jan-18 7:06 
QuestionI am Getting "System.NullReferenceException: Object reference not set to an instance of an object." Pin
Member 114379002-Dec-17 17:19
Member 114379002-Dec-17 17:19 
PraiseThank you! Pin
wesbyte9-Aug-17 21:02
wesbyte9-Aug-17 21:02 
QuestionThank you Pin
Member 1169717517-Mar-17 17:33
Member 1169717517-Mar-17 17:33 
QuestionThanks Pin
Vyacheslav Chernykh15-Oct-16 14:34
Vyacheslav Chernykh15-Oct-16 14:34 
QuestionThank you so much :D Pin
mr four4-Sep-16 0:15
mr four4-Sep-16 0:15 
GeneralRe: Thank you so much :D Pin
Sharad Chandra Pyakurel4-Sep-16 3:41
Sharad Chandra Pyakurel4-Sep-16 3:41 
GeneralMy vote of 5 Pin
Member 1254234823-May-16 21:11
Member 1254234823-May-16 21:11 
GeneralRe: My vote of 5 Pin
Sharad Chandra Pyakurel23-May-16 21:50
Sharad Chandra Pyakurel23-May-16 21:50 
QuestionDrag items / reorder list Pin
Peter Slana23-May-16 2:58
Peter Slana23-May-16 2:58 
Praisemy vote of 5... CHEERS!!! Pin
Sudarshan Poudel9-Apr-16 21:51
professionalSudarshan Poudel9-Apr-16 21:51 
QuestionNice Article Pin
Jerry7228-Apr-16 11:33
professionalJerry7228-Apr-16 11:33 
GeneralSource code download link is not working Pin
Hanumantha reddy GS6-Apr-16 1:10
Hanumantha reddy GS6-Apr-16 1:10 
GeneralRe: Source code download link is not working Pin
Sharad Chandra Pyakurel6-Apr-16 1:12
Sharad Chandra Pyakurel6-Apr-16 1:12 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.