Xamarin.Android - Working With MongoDB

Introduction

In this article, I will show you how to create a MongoDB database and how to work with it using Xamarin.Android. MongoDB is a document database with the scalability and flexibility that you want with querying and indexing of the data.

Collection in MongoDB

A collection is a group of MongoDB documents. It is equivalent to an RDBMS table. A collection exists within a single database. The collection does not enforce a schema. Documents within a collection can have different fields. Typically, all documents in a collection are of similar or related purpose.

Document in MongoDB

A document is a set of key-value pairs. Documents have a dynamic schema. Dynamic schema means that the document in the same collection does not need to have the same set of fields or structure, and common fields in a collection's document may hold different types of data.

Relationship of RDBMS with MongoDB

RDBMSMongoDB
DatabaseDatabase
TableCollection
Tuple/RowDocument
ColumnField
Table JoinEmbedded Document
Primary KeyPrimary Key(Default Key _id provided by MongoDB itself)
 
About MLAB 

MLab is a fully managed cloud database service that hosts MongoDB database. MLab is based on the cloud providers like Amazon, Google, and Microsoft Azure, and has partnered with Platform-as-a-Service provider.

Create a Mongo Database

Step 1

Go to this URL - https://mlab.com

Step 2

Click on "GET STARTED INSTANTLY with 500 MB FREE" and create a new database.



Step 3

Next, select a cloud provider. All the three are free for users. Just select the Plan Type as SANDBOX.



Step 4

Choose the desired Azure region and hit "Continue".

 

Step 5
  
Next, put the database name and hit OK.

 

Step 6

Next, add a new collection.

 

 

Step 7

Add a new Document inside the collection.



Step 8

Now, you need to have an API key that will be consumed in the mobile app. Access of these RESTful APIs is disabled by default. Go to User Profile and enable the Generate API key.

 

Xamarin Android Application

Step 1

Open Visual Studio and go to New Project-> Templates-> Visual C#-> Android-> Blank app. Give it a name, like MongoDB.

 

Step 2

Next, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name, like Common.cs and write the following code with appropriate namespaces.

(Class Name: Common)

Common class code 
  1. using System.Text;  
  2. using System.Linq;  
  3. using System;  
  4. using CloudNoSQL.Class;  
  5. namespace CloudNoSQL.Helper {  
  6.     class Common {  
  7.         private static String DB_NAME = "xamarindb";  
  8.         private static String COLLECTION_NAME = "user";  
  9.         private static String API_KEY = "ow6xCr4R6mh9Ac-WnOEYe31Uv-4-j5nh";  
  10.         public static string getAddressSingle(User user) {  
  11.             String baseUrl = $ "https://api.mlab.com/api/1/databases/{DB_NAME}/collections/{COLLECTION_NAME}";  
  12.             StringBuilder strBuilder = new StringBuilder(baseUrl);  
  13.             strBuilder.Append("/" + user._id.oid + "?apiKey=" + API_KEY);  
  14.             return strBuilder.ToString();  
  15.         }  
  16.         public static string GetAddressAPI() {  
  17.             String baseUrl = $ "https://api.mlab.com/api/1/databases/{DB_NAME}/collections/{COLLECTION_NAME}";  
  18.             StringBuilder strBuilder = new StringBuilder(baseUrl);  
  19.             strBuilder.Append("?apiKey=" + API_KEY);  
  20.             return strBuilder.ToString();  
  21.         }  
  22.     }  

Step 3 

Similarly, create another class named as HttpDataHandler.cs and write the following code with appropriate namespaces.

(File Name: HttpDataHandler)

  1. using System;  
  2. using System.Text;  
  3. using Java.Net;  
  4. using Java.IO;  
  5. using System.IO;  
  6. namespace CloudNoSQL.Class {  
  7.     public class HttpDataHandler {  
  8.         static String stream = null;  
  9.         public HttpDataHandler() {}  
  10.         public String GetHTTPData(String urlString) {  
  11.             try {  
  12.                 URL url = new URL(urlString);  
  13.                 HttpURLConnection urlConnection = (HttpURLConnection) url.OpenConnection();  
  14.                 if (urlConnection.ResponseCode == HttpStatus.Ok) // 200  
  15.                 {  
  16.                     BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.InputStream));  
  17.                     StringBuilder sb = new StringBuilder();  
  18.                     String line;  
  19.                     while ((line = r.ReadLine()) != null) sb.Append(line);  
  20.                     stream = sb.ToString();  
  21.                     urlConnection.Disconnect();  
  22.                 }  
  23.             } catch (Exception ex) {  
  24.                 System.Console.WriteLine("{0} Exception caught.", ex);  
  25.             }  
  26.             return stream;  
  27.         }  
  28.         public void PostHTTPData(String urlString, String json) {  
  29.             try {  
  30.                 URL url = new URL(urlString);  
  31.                 HttpURLConnection urlConnection = (HttpURLConnection) url.OpenConnection();  
  32.                 urlConnection.RequestMethod = "POST";  
  33.                 urlConnection.DoOutput = true;  
  34.                 byte[] _out = Encoding.UTF8.GetBytes(json);  
  35.                 int lenght = _out.Length;  
  36.                 urlConnection.SetFixedLengthStreamingMode(lenght);  
  37.                 urlConnection.SetRequestProperty("Content-Type""application/json");  
  38.                 urlConnection.SetRequestProperty("charset""utf-8");  
  39.                 urlConnection.Connect();  
  40.                 try {  
  41.                     Stream str = urlConnection.OutputStream;  
  42.                     str.Write(_out, 0, lenght);  
  43.                 } catch (Exception ex) {  
  44.                     System.Console.WriteLine("{0} Exception caught.", ex);  
  45.                 }  
  46.                 var status = urlConnection.ResponseCode;  
  47.             } catch (Exception ex) {  
  48.                 System.Console.WriteLine("{0} Exception caught.", ex);  
  49.             }  
  50.         }  
  51.         public void PutHTTPData(String urlString, String json) {  
  52.             try {  
  53.                 URL url = new URL(urlString);  
  54.                 HttpURLConnection urlConnection = (HttpURLConnection) url.OpenConnection();  
  55.                 urlConnection.RequestMethod = "PUT";  
  56.                 urlConnection.DoOutput = true;  
  57.                 byte[] _out = Encoding.UTF8.GetBytes(json);  
  58.                 int lenght = _out.Length;  
  59.                 urlConnection.SetFixedLengthStreamingMode(lenght);  
  60.                 urlConnection.SetRequestProperty("Content-Type""application/json");  
  61.                 urlConnection.SetRequestProperty("charset""utf-8");  
  62.                 urlConnection.Connect();  
  63.                 try {  
  64.                     Stream str = urlConnection.OutputStream;  
  65.                     str.Write(_out, 0, lenght);  
  66.                 } catch (Exception ex) {  
  67.                     System.Console.WriteLine("{0} Exception caught.", ex);  
  68.                 }  
  69.                 var status = urlConnection.ResponseCode;  
  70.             } catch (Exception ex) {  
  71.                 System.Console.WriteLine("{0} Exception caught.", ex);  
  72.             }  
  73.         }  
  74.         public void DeleteHTTPData(String urlString, String json) {  
  75.             try {  
  76.                 URL url = new URL(urlString);  
  77.                 HttpURLConnection urlConnection = (HttpURLConnection) url.OpenConnection();  
  78.                 urlConnection.RequestMethod = "DELETE";  
  79.                 urlConnection.DoOutput = true;  
  80.                 byte[] _out = Encoding.UTF8.GetBytes(json);  
  81.                 int lenght = _out.Length;  
  82.                 urlConnection.SetFixedLengthStreamingMode(lenght);  
  83.                 urlConnection.SetRequestProperty("Content-Type""application/json");  
  84.                 urlConnection.SetRequestProperty("charset""utf-8");  
  85.                 urlConnection.Connect();  
  86.                 try {  
  87.                     Stream str = urlConnection.OutputStream;  
  88.                     str.Write(_out, 0, lenght);  
  89.                 } catch (Exception ex) {  
  90.                     System.Console.WriteLine("{0} Exception caught.", ex);  
  91.                 }  
  92.                 var status = urlConnection.ResponseCode;  
  93.             } catch (Exception ex) {  
  94.                 System.Console.WriteLine("{0} Exception caught.", ex);  
  95.             }  
  96.         }  
  97.     }  
  98. }  
Step 4

Now, open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open this main layout file and add the following code.
(File Name: Main.axml)
(Folder Name: Layout)
 
Complete Code of UI 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:minWidth="25px" android:minHeight="25px">  
  3.     <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">  
  4.         <TextView android:text="User :" android:textColor="#800000" android:layout_width="wrap_content" android:layout_height="wrap_content" />  
  5.         <EditText android:id="@+id/edtUser" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Enter User Name..." /> </LinearLayout>  
  6.     <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">  
  7.         <Button android:id="@+id/btnAdd" android:text="Add" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#008000" />  
  8.         <Button android:id="@+id/btnEdit" android:text="Edit" android:textColor="#0000FF" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  9.         <Button android:id="@+id/btnDelete" android:text="Delete" android:textColor="#FF0000" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>  
  10.     <ListView android:id="@+id/lstView" android:layout_width="match_parent" android:layout_height="wrap_content" />   
  11. </LinearLayout>  

Layout

 

Step 5

Next, we need to add a CustomAdapter class. Write the following code in it with appropriate namespaces.
(File Name: CustomAdapter)
  1. using Android.Content;  
  2. using System.Collections.Generic;  
  3. using Android.Views;  
  4. using Android.Widget;  
  5. using CloudNoSQL.Class;  
  6. namespace CloudNoSQL.Helper {  
  7.     public class CustomAdapter: BaseAdapter {  
  8.         private Context mContext;  
  9.         private List < User > users;  
  10.         public CustomAdapter(Context mContext, List < User > users) {  
  11.             this.mContext = mContext;  
  12.             this.users = users;  
  13.         }  
  14.         public override int Count {  
  15.             get {  
  16.                 return users.Count;  
  17.             }  
  18.         }  
  19.         public override Java.Lang.Object GetItem(int position) {  
  20.             {  
  21.                 return position;  
  22.             }  
  23.         }  
  24.         public override long GetItemId(int position) {  
  25.             return position;  
  26.         }  
  27.         public override View GetView(int position, View convertView, ViewGroup parent) {  
  28.             LayoutInflater inflater = (LayoutInflater) mContext.GetSystemService(Context.LayoutInflaterService);  
  29.             View view = inflater.Inflate(Resource.Layout.row, null);  
  30.             TextView txtUser = view.FindViewById < TextView > (Resource.Id.txtUser);  
  31.             txtUser.Text = users[position].user;  
  32.             return view;  
  33.         }  
  34.     }  
  35. }  
Step 6

Next, we need to add another layout, so open Solution Explorer-> Project Name-> Resources-> Layout -> Right-click to Add-> New Item-> Layout. Give it a name as row and add the following code. 
 
(File Name: row.axml)
(Folder Name: Layout)
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <TextView android:text="Large Text" android:textColor="#000000" android:textAppearance="?android:attr/textAppearanceLarge" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/txtUser" />   
  4. </LinearLayout>  
Step 7

Let's open Solution Explorer-> Properties-> AndroidManifest and let's add the below code inside application tags. 
  1. <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />  
  2. <uses-permission android:name="android.permission.INTERNET" />  
Step 8

Now, go to Solution Explorer-> Project Name-> References. Then, right-click to "Manage NuGet Packages" and search for JSON. Install the Newtonsoft.Json Packages.

 

Step 10

Open Solution Explorer-> Project Name-> MainActivity. Open the main activity file and add the following code with appropriate namespaces.

Main Activity
  1. using Android.App;  
  2. using Android.Widget;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using CloudNoSQL.Class;  
  6. using System.Collections.Generic;  
  7. using static Android.Widget.AdapterView;  
  8. using Android.Views;  
  9. using Java.Lang;  
  10. using Newtonsoft.Json;  
  11. using CloudNoSQL.Helper;  
  12. namespace CloudNoSQL {  
  13.     [Activity(Label = "CloudNoSQL", MainLauncher = true, Theme = "@style/Theme.AppCompat.Light")]  
  14.     public class MainActivity: AppCompatActivity, IOnItemClickListener {  
  15.         //globle Variables  
  16.         private ListView lstView;  
  17.         private Button btnAdd, btnEdit, btnDelete;  
  18.         private EditText edtUser;  
  19.         private User SelectedUser = null;  
  20.         private List < User > users;  
  21.         public void OnItemClick(AdapterView parent, View view, int position, long id) {  
  22.             SelectedUser = users[position];  
  23.             edtUser.Text = SelectedUser.user; //Set Username to Edit Text  
  24.         }  
  25.         protected override void OnCreate(Bundle savedInstanceState) {  
  26.             base.OnCreate(savedInstanceState);  
  27.             // Set our view from the "main" layout resource  
  28.             SetContentView(Resource.Layout.Main);  
  29.             lstView = FindViewById < ListView > (Resource.Id.lstView);  
  30.             btnAdd = FindViewById < Button > (Resource.Id.btnAdd);  
  31.             btnEdit = FindViewById < Button > (Resource.Id.btnEdit);  
  32.             btnDelete = FindViewById < Button > (Resource.Id.btnDelete);  
  33.             edtUser = FindViewById < EditText > (Resource.Id.edtUser);  
  34.             //Add Event to Control  
  35.             lstView.OnItemClickListener = this;  
  36.             //On Add button Click  
  37.             btnAdd.Click += delegate {  
  38.                 new PostData(edtUser.Text, this).Execute(Common.GetAddressAPI());  
  39.             };  
  40.             //On Edit Button Click  
  41.             btnEdit.Click += delegate {  
  42.                 new PutData(SelectedUser, edtUser.Text, this).Execute(Common.getAddressSingle(SelectedUser));  
  43.             };  
  44.             //On Delete Button Click  
  45.             btnDelete.Click += delegate {  
  46.                 new DeleteData(SelectedUser, edtUser.Text, this).Execute(Common.getAddressSingle(SelectedUser));  
  47.             };  
  48.             //Load Data when opened app  
  49.             new GetData(this).Execute(Common.GetAddressAPI());  
  50.         }  
  51.         //User Inner Class for process data  
  52.         private class GetData: AsyncTask < string, Java.Lang.Void, string > {  
  53.             private ProgressDialog pd = new ProgressDialog(Application.Context);  
  54.             private MainActivity activity;  
  55.             public GetData(MainActivity activity) {  
  56.                 this.activity = activity;  
  57.             }  
  58.             protected override void OnPreExecute() {  
  59.                 base.OnPreExecute();  
  60.                 pd.Window.SetType(WindowManagerTypes.SystemAlert);  
  61.                 pd.SetTitle("Please wait...");  
  62.                 pd.Show();  
  63.             }  
  64.             protected override string RunInBackground(params string[] @params) {  
  65.                 string stream = null;  
  66.                 string urlString = @params[0];  
  67.                 HttpDataHandler http = new HttpDataHandler();  
  68.                 stream = http.GetHTTPData(urlString);  
  69.                 return stream;  
  70.             }  
  71.             protected override void OnPostExecute(string result) {  
  72.                 base.OnPostExecute(result);  
  73.                 activity.users = JsonConvert.DeserializeObject < List < User >> (result);  
  74.                 CustomAdapter adapter = new CustomAdapter(Application.Context, activity.users);  
  75.                 activity.lstView.Adapter = adapter;  
  76.                 pd.Dismiss();  
  77.             }  
  78.         }  
  79.         //PostData Class  
  80.         private class PostData: AsyncTask < string, Java.Lang.Void, string > {  
  81.             private ProgressDialog pd = new ProgressDialog(Application.Context);  
  82.             string userName = "";  
  83.             private MainActivity mainActivity;  
  84.             public PostData(string userName, MainActivity mainActivity) {  
  85.                 this.userName = userName;  
  86.                 this.mainActivity = mainActivity;  
  87.             }  
  88.             protected override void OnPreExecute() {  
  89.                 base.OnPreExecute();  
  90.                 pd.Window.SetType(WindowManagerTypes.SystemAlert);  
  91.                 pd.SetTitle("Please wait...");  
  92.                 pd.Show();  
  93.             }  
  94.             protected override string RunInBackground(params string[] @params) {  
  95.                 string urlString = @params[0];  
  96.                 HttpDataHandler http = new HttpDataHandler();  
  97.                 User user = new User();  
  98.                 user.user = userName;  
  99.                 string json = JsonConvert.SerializeObject(user);  
  100.                 http.PostHTTPData(urlString, json);  
  101.                 return string.Empty;  
  102.             }  
  103.             protected override void OnPostExecute(string result) {  
  104.                 base.OnPostExecute(result);  
  105.                 new GetData(mainActivity).Execute(Common.GetAddressAPI());  
  106.                 pd.Dismiss();  
  107.             }  
  108.         }  
  109.         //PutData Class  
  110.         private class PutData: AsyncTask < string, Java.Lang.Void, string > {  
  111.             private ProgressDialog pd = new ProgressDialog(Application.Context);  
  112.             string newUser = "";  
  113.             private MainActivity mainActivity;  
  114.             User selectedUser = null;  
  115.             public PutData(User selectedUser, string newUser, MainActivity mainActivity) {  
  116.                 this.newUser = newUser;  
  117.                 this.mainActivity = mainActivity;  
  118.                 this.selectedUser = selectedUser;  
  119.             }  
  120.             protected override void OnPreExecute() {  
  121.                 base.OnPreExecute();  
  122.                 pd.Window.SetType(WindowManagerTypes.SystemAlert);  
  123.                 pd.SetTitle("Please wait...");  
  124.                 pd.Show();  
  125.             }  
  126.             protected override string RunInBackground(params string[] @params) {  
  127.                 string urlString = @params[0];  
  128.                 HttpDataHandler http = new HttpDataHandler();  
  129.                 selectedUser.user = newUser;  
  130.                 string json = JsonConvert.SerializeObject(selectedUser);  
  131.                 http.PutHTTPData(urlString, json);  
  132.                 return string.Empty;  
  133.             }  
  134.             protected override void OnPostExecute(string result) {  
  135.                 base.OnPostExecute(result);  
  136.                 new GetData(mainActivity).Execute(Common.GetAddressAPI());  
  137.                 pd.Dismiss();  
  138.             }  
  139.         }  
  140.         //DeleteData Class  
  141.         private class DeleteData: AsyncTask < string, Java.Lang.Void, string > {  
  142.             private ProgressDialog pd = new ProgressDialog(Application.Context);  
  143.             string newUser = "";  
  144.             private MainActivity mainActivity;  
  145.             User selectedUser = null;  
  146.             public DeleteData(User selectedUser, string newUser, MainActivity mainActivity) {  
  147.                 this.newUser = newUser;  
  148.                 this.mainActivity = mainActivity;  
  149.                 this.selectedUser = selectedUser;  
  150.             }  
  151.             protected override void OnPreExecute() {  
  152.                 base.OnPreExecute();  
  153.                 pd.Window.SetType(WindowManagerTypes.SystemAlert);  
  154.                 pd.SetTitle("Please wait...");  
  155.                 pd.Show();  
  156.             }  
  157.             protected override string RunInBackground(params string[] @params) {  
  158.                 string urlString = @params[0];  
  159.                 HttpDataHandler http = new HttpDataHandler();  
  160.                 selectedUser.user = newUser;  
  161.                 string json = JsonConvert.SerializeObject(selectedUser);  
  162.                 http.DeleteHTTPData(urlString, json);  
  163.                 return string.Empty;  
  164.             }  
  165.             protected override void OnPostExecute(string result) {  
  166.                 base.OnPostExecute(result);  
  167.                 new GetData(mainActivity).Execute(Common.GetAddressAPI());  
  168.                 pd.Dismiss();  
  169.             }  
  170.         }  
  171.     }  
  172. }  
Output

Up Next
    Ebook Download
    View all
    Learn
    View all