Parse JSON using GSON in kotlin

In this article I’ll show you the easiest way to parse JSON data using GSON and kotlin.

Let’s take the JSON example below:
[
{
"question": "Which method is use to launch an activity?",
"answer": "startActivity()"
},
{
"question": "The plus(+) means in statement android:id=\"@+id/my_id\"?",
"answer": "Create new id and add to resources"
},
{
"question": "When does onResume() method called?",
"answer": "called when the activity come to foreground."
},
{
"question": "Where will we declare the activity for the system can find it?",
"answer": "AndroidManifest.xml"
},
{
"question": "What does the .apk extension stand for?",
"answer": "Application Package"
}
]
view raw questions.json hosted with ❤ by GitHub
To use GSON, add the dependency in build.gradle file:
Create the data class relative the the JSON we want to parse:
And finally, the code below is to be used to get a parsed list of questions (json file is in raw resources folder):

Hands on Xamarin Platform Pipeline – Build – Setup automatic build on git push

In this article I’ll show you how to setup the automatic build of our ‘RememberIt’ application after every git push using Visual Studio Mobile Center.

The automatic building of the application will help to ensure that in a team of developers the application is always building successfully and is available for distribution. When the build is broken, it can be seen and solved quickly.

If not yet done, please read the previous post in the Hands on Xamarin Platform Pipeline series.

To start, browse to Visual Studio Mobile Center then select the application we created on the previous post.

Select Build menu, the supported version control system are:
– Visual Studio Team Services
– Github
– Bitbucket
In our case, we’ll use Github.

Authorize Mobile Center to access to your Github repositories.
Select the repository where ‘RememberIt’ application is hosted.
Select the desired branch, in our case it’s the master branch.

Now, select the connected application project, then:
– Select Debug or Release configuration
– Activate Build on push option in order to build the project on every available push

Activate the Sign builds option in order to sign the application after the build. 
In this case, we need to provide the keystore. We’ll use the debug keystore which is automatically generated.
Select the keystore in: ‘~/.local/share/Xamarin/Mono for Android/debug.keystore’
Keystore password: android
Key Alias: androiddebugkey
Key password: android
The first Build is queued waiting for an available machine to start the build. We can eventually fire a manual build by pushing ‘Build now’ button.
In the console we can see the build progress.
And after some unsuccessful builds and adjustments in the code. We will be able to see a successful build.
We will be able to either distribute the application or download the generated apk as well as the build logs.
See you soon.

Hands on Xamarin Platform Pipeline – Develop – Add Facebook authentication

In this article I’ll show you how to add Facebook authentication to the “RememberIt” mobile application.

If not yet done, please read the previous post in the Hands on Xamarin Platform Pipeline series.

Facebook app creation

In order to be able to add Facebook authentication, we need to create a Facebook App. To do this, navigate to: https://developers.facebook.com/apps, click on “Add a New App” button then fill in the application information.
Go to Settings then copy the App ID.
Then always in Settings, click on Add Platform then Select Android.
Fill in the following information:
– Google Play Package Name: the package name defined in Android Manifest file.
– Class Name: MainActivity in our case.
– Key Hashes: where we can add Debug and Release Android key hashes. To generate the Debug Key hash, open the terminal then run the command below:
keytool -exportcert -alias androiddebugkey -keystore ~/.local/share/Xamarin/Mono\ for\ Android/debug.keystore | openssl sha1 -binary | openssl base64
view raw gistfile1.txt hosted with ❤ by GitHub
Use ‘android’ as password then copy-paste the generated hash key.
Now, click on Add Product under Products category then choose Facebook Login.
Now, activate all the OAuth parameters and use the URL: https://www.facebook.com/connect/login_success.html as Valid OAuth redirect URL.
Finally, we can make our Facebook application public under App Review menu as shown below.

Add Facebook authentication to RememberIt application

For this, we will use the great Xamarin Component Xamarin.Auth, for more details you can check the official documentation.
Within the project, double click on Components then search for Xamarin.Auth.
Click on ‘Add to App’, once installed we can browse some samples as well as the documentation directly on Xamarin IDE.
Now, within the project double click on References then add the assembly System.Json.
Modify the manifest file to add internet permission and app_id meta data as presented below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android&quot; android:versionCode="1" android:versionName="1.0" package="com.anas.rememberit">
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.INTERNET"/>
<application android:allowBackup="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:theme="@style/AppTheme">
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
</application>
</manifest>
Open the Main.axml layout then add the facebook button.
<Button
android:id="@+id/fbButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="LOGIN WITH FACEBOOK" />
view raw Main.axml hosted with ❤ by GitHub
On the MainActivity class create a static TaskScheduler for UI.
// UI Scheduler
static readonly TaskScheduler UIScheduler = TaskScheduler.FromCurrentSynchronizationContext();
view raw MainActivity.cs hosted with ❤ by GitHub
Then, create a method LoginToFacebook that will perform all the job. Below the documented source code of the method:
void LoginToFacebook(bool allowCancel)
{
var auth = new OAuth2Authenticator(
clientId: "395508370820207", // APP ID retrieved from Facebook created Application
scope: "email", // the scopes for the API
authorizeUrl: new Uri("https://m.facebook.com/dialog/oauth/&quot;), // the auth URL for the service
redirectUrl: new Uri("https://www.facebook.com/connect/login_success.html&quot;));
// To allow cancel of the authentication
auth.AllowCancel = allowCancel;
// If authorization succeeds or is canceled, .Completed will be fired.
auth.Completed += (s, ee) =>
{
if (!ee.IsAuthenticated)
{
// Not Authenticated
var builder = new AlertDialog.Builder(this);
builder.SetMessage("Not Authenticated");
builder.SetPositiveButton("Ok", (o, e) => { });
builder.Create().Show();
return;
}
// Now that we're logged in, make a OAuth2 request to get the user's info.
var request = new OAuth2Request("GET", new Uri("https://graph.facebook.com/me&quot;), null, ee.Account);
request.GetResponseAsync().ContinueWith(t =>
{
if (t.IsFaulted)
{
// Problem in authentication
var builder = new AlertDialog.Builder(this);
builder.SetTitle("Error");
builder.SetMessage(t.Exception.Flatten().InnerException.ToString());
builder.SetPositiveButton("Ok", (o, e) => { });
builder.Create().Show();
}
else if (!t.IsCanceled)
{
// Authentication succeeded, show the toast then go the main activity
var obj = JsonValue.Parse(t.Result.GetResponseText());
Toast.MakeText(this, string.Format("Welcome {0}.", obj["name"]), ToastLength.Long).Show();
StartActivity(typeof(RememberListActivity));
}
}, UIScheduler);
};
var intent = auth.GetUI(this);
StartActivity(intent);
}
view raw MainActivity.cs hosted with ❤ by GitHub
Now, all we need to do is to wire the method to the button click, add the following code in the OnCreate method:
// Facebook Authentication
Button fbButton = FindViewById<Button>(Resource.Id.fbButton);
fbButton.Click += (sender, args) =>
{
LoginToFacebook(true);
};
view raw MainActivity.cs hosted with ❤ by GitHub
Build, Deploy and …
Complete source code is available on GitHub.
See you soon!

Hands on Xamarin Platform Pipeline – Develop – Exploring Visual Studio Mobile Center

In this post we’ll explore the functionalities of the Visual Studio Mobile Center, it’s just an overview and each functionality will be detailed in future posts while improving our ‘RememberIt’ application.

Don’t forget to take a look at the previous posts.
Visual Studio Mobile Center helps mobile developers to cover all the lifecycle (Continuous Integration and Continuous Delivery) and the functionalities they need for a mobile application. It’s available under the following link: https://mobile.azure.com

Application creation

Let’s create our ‘RememberIt’ application is Visual Studio Mobile Center. Firstly, login to https://mobile.azure.com, then push ‘Add new app’ button.
Enter app name and for our ‘RememberIt’ application select Android as OS, Xamarin as platform then push ‘Add new app’ button.
Once the application created, the getting started page is shown.

Exploring Visual Studio Mobile Center menus

Build menu: to retrieve the code from either GitHub repository or Bitbucket then configure an automatic build of the project.
Test menu: it’s for UI automation tests, we can chose the device configuration and plan UI testing after the build step.
Distribute menu: for distribution and where we can define group of testers and configure an automatic distribution to that group after a successful build.
Tables menu: is for managing the storage of the mobile application. 
Identity menu: is for adding authentication to the mobile application and the following providers are supported:
– Azure Active Directory
– Microsoft account
– Facebook
– Google
– Twitter
Crashes menu: is for crash data browsing of the mobile application.
Analytics menu: is for mobile application analytics data browsing.

Hands on Xamarin Platform Pipeline – Develop – Let’s explore some nice features of Xamarin Studio 6

This is not the post that logically follows the the previous one but I suggest to read it. In this post we’ll take a break and explore some nice features of Xamarin Studio 6.

General functionalities

Dark theme is one of the new features, in preferences then Visual Style.
We can configure the desired code formatting between Visual Studio Style, Mono Style or Custom Style. To do this: preference, source code, code formatting then Text file where we can define the Policy, use 4 spaces instead of tabs… Just make sure to have the other types (XML, F# and C#) use the default behavior of Text file.
Global Search can be used to search for everything inside the workspace: files, Xamarin Studio functionalities & commands…
When we copy a piece of code, it will be saved in the clipboard inside the toolbox. This piece of code can be dragged and dropped to a source code file.
When we search for something we can pin the results to save them and do other searches.
We can highlight the current line, show invisible characters (like spaces for example).
We can go to a declaration just by hovering it using the cursor and Command+D keys or mouse clicking and Command key. Also, we can use the next-back buttons to navigate next and back.
We can have multiple windows in case we work in multiple monitors. Just drag the document outside the IDE.
We can also have a side by side view for comparison needs for example, just drag the document.

Code completion and analysis

Thanks to Roslyn processor, the code completion becomes asynchronous as well as live code analysis that shows up: warnings in orange and hints in green color.
Select the warning and the hint then hit Alt+Enter to see suggestions about the solution.
Activate fix imports option in order to have the imports added automatically while writing the code.

Refactoring options

alt-up down to move the current line.
We can also select by logical scope using alt-shift up down then alt-enter to have refactoring suggestions.
Please note that we can create a bug in Xamarin Studio BugTracker as well as suggest new functionalities in Uservoice.

Hands on Xamarin Platform Pipeline – Develop – Add authentication using Azure Active Directory

After creating an offline application following the previous post.

Now, we will start convert our offline application to a connected one using Microsoft Azure tools. In this post we’ll add authentication using Azure Active Directory.

Application Creation on Azure Active Directory

To do this, login to https://manage.windowsazure.com and in case you don’t have Azure Subscription a trial can be requested. Then, click on Active Directory as shown in the image below.

Select an Active Directory, navigate to Applications tab, click ‘Add‘ button then select ‘Add an application my organization is developing‘.
Choose an application name and make sure to select ‘Native Client Application‘ as type of application.
On the final screen, provide the ‘Redirect URI‘ then validate the application creation.
Once the app is created, navigate to ‘Configure‘ tab then write down the ‘Client ID’ that we’ll use later.

User Creation on Active Directory

In Active Directory main screen, navigate to Users tab, click on Add User button then chose a user name, in my case the user name shall be: test@anasehhotmail.onmicrosoft.com
Fill in some information about the user.
At the last step generate a temporary password that we can use for the first authentication in order to chose the final password.

Update the mobile Application

Add the package named Azure Active Directory Authentication Library (Azure ADAL) to the application.
Add a button to the Main.axml layout, we can use the Android graphical designer.
In the MainActivity class add the following constants.
// Client ID
public static string clientId = "2a6ce4df-f26f-4864-bb28-7f806abbcc67";
public static string commonAuthority = "https://login.windows.net/common&quot;;
// Redirect URI
public static Uri returnUri = new Uri("http://rememberit-redirect&quot;);
// Graph URI
const string graphResourceUri = "https://graph.windows.net&quot;;
public static string graphApiVersion = "2013-11-08";
// AuthenticationResult will hold the result after authentication completes
AuthenticationResult authResult = null;
view raw MainActivity.cs hosted with ❤ by GitHub
Now, invoke the authentication process then save the result to authResult variable.
Button adalButton = FindViewById<Button>(Resource.Id.adalButton);
adalButton.Click += async (sender, args) =>
{
var authContext = new AuthenticationContext(commonAuthority);
if (authContext.TokenCache.ReadItems().Count() > 0)
{
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
}
authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new PlatformParameters(this));
if ((authResult != null) && !string.IsNullOrEmpty(authResult.AccessToken))
{
Toast.MakeText(this, string.Format("Welcome {0} {1}.", authResult.UserInfo.GivenName,
authResult.UserInfo.FamilyName), ToastLength.Long).Show();
StartActivity(typeof(RememberListActivity));
}
};
view raw MainActivity.cs hosted with ❤ by GitHub
Finally, override the OnActivityResult method to get the authentication result.
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
AuthenticationAgentContinuationHelper.SetAuthenticationAgentContinuationEventArgs(requestCode, resultCode, data);
}
view raw MainActivity.cs hosted with ❤ by GitHub
Below some screenshots.

Complete source code can be found on Github.

See you soon!

Hands on Xamarin Platform Pipeline – Develop – Let’s start by an offline application

After configuring the development environment following the previous post.

Now, we’ll be able to start developing mobile applications using Xamarin Platform.
In this post we’ll start by creating the offline version of our “Remember It” application.

Application Creation

Open Xamarin Studio IDE, please note that I’m using dark theme because I’m fan of it and the default theme that comes after fresh Xamarin installation is the light theme.
Click on “New Solution…” button then select Android App.
Fill in the application Name, Organization Identifier. For the Target Platform I chose ‘Maximum Compatibility’ to cover multiple Android versions (since 2.3), and finally I chose AppCompat Light theme to bring Material Design to my Android application.
In the final step, we can set the project name, the solution name and the project location. I checked the Xamarin Test Cloud option in order to create UI Test project that we’ll use after.
If you’re getting build errors related to styles and theme, just make sure that Android Support V4 and V7 are correctly installed. Double click on Packages section within the project and add Android Support V4 and V7 as described bellow.
Now, the application should be built without any problem.

Android Emulator Creation

In Tools menu we can open the Google Emulator Manager.
Let’s create a Nexus 6 emulator by filling some information about the device, choosing x86_64 as CPU is only to have faster emulator.
Now, we should be able to deploy applications to the created device.
We can start the device to verify whether it’s working correctly.

Deploy the application to the device

Just select the new created device.
And push Play button, we’ll get the Xamarin Hello World Application.
We can also put some breakpoints in the code to debug.

Create Login Screen

We can use the Android graphical designer to place UI components and change their properties.
Let’s create the activity that will hold the list and come after the login step.
using Android.App;
using Android.OS;
namespace RememberIt
{
[Activity(Label = "Things to remember")]
public class RememberListActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.RememberList);
}
}
}
Create the corresponding empty layout for the moment.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Now, once we click on ‘LOGIN’ button in Login screen, we should be able to go to the new created activity, the Main activity shall become as follows:
using Android.App;
using Android.Widget;
using Android.OS;
namespace RememberIt
{
[Activity(Label = "Welcome to Remember!", MainLauncher = true, Icon = "@mipmap/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.myButton);
button.Click += delegate { StartActivity(typeof(RememberListActivity)); };
}
}
}
view raw MainActivity.cs hosted with ❤ by GitHub
At this stage, we’ll have the login screen as follows and once we click on login button we should be able to go to an empty screen.

Add toolbar and plus menu button to add elements

You can notice that the RememberListActivity does not contain the toolbar, let’s add it.
First, we need to define some material colors and the theme under Resources/values/Styles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<resources>
<style name="AppTheme" parent="@style/Theme.AppCompat.Light.NoActionBar">
<item name="android:colorPrimary">@color/primary</item>
<item name="android:colorPrimaryDark">@color/primary_dark</item>
<item name="android:colorAccent">@color/accent</item>
</style>
</resources>
view raw Styles.xml hosted with ❤ by GitHub
And material colors in Resources/values/Colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="primary">#03A9F4</color>
<color name="primary_dark">#0288D1</color>
<color name="accent">#E040FB</color>
</resources>
view raw Colors.xml hosted with ❤ by GitHub
Finally, modify the Android manifest (Properties/AndroidManifest.xml) to choose the new theme.
<application android:theme="@style/AppTheme" />
The toolbar can be added to the view in RememberList.axml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
xmlns:app="http://schemas.android.com/apk/res-auto&quot;
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/primary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
</LinearLayout>
Now, create the menu in Resources/menu/MainMenu.xml
<menu
xmlns:android="http://schemas.android.com/apk/res/android&quot;
xmlns:app="http://schemas.android.com/apk/res-auto"&gt;
<item
android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:title="Add"
app:showAsAction="ifRoom"/>
</menu>
view raw MainMenu.xml hosted with ❤ by GitHub
And, do some adjustments in the RememberListActivity
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
namespace RememberIt
{
[Activity(Label = "Things to remember")]
public class RememberListActivity : AppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.RememberList);
// Setup the toolbar
Toolbar myToolbar = (Toolbar)FindViewById(Resource.Id.my_toolbar);
SetSupportActionBar(myToolbar);
}
public override bool OnOptionsItemSelected(Android.Views.IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_add:
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public override bool OnCreateOptionsMenu(Android.Views.IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.MainMenu, menu);
return base.OnCreateOptionsMenu(menu);
}
}
}
Deploy and…

Create the “Remember It” list

We will use the Android RecyclerView and CardView, so we need to add the two components to the project.
The RememberList layout will become:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
xmlns:app="http://schemas.android.com/apk/res-auto&quot;
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="@color/primary"
android:elevation="4dp"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_below="@+id/my_toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Now, let’s populate the recycler view and for this we’ll start by creating the model class.
using System;
namespace RememberIt
{
public class RememberThing
{
public string Name { get; set; }
public DateTime Deadline { get; set; }
public RememberThing()
{
}
}
}
view raw RememberIt.cs hosted with ❤ by GitHub
Then, the RecyclerView element layout where we’ll add our CardView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android&quot;
xmlns:card_view="http://schemas.android.com/apk/res-auto&quot;
android:id="@+id/cardview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardUseCompatPadding="true"
card_view:cardElevation="5dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp">
<TextView
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="(name)" />
<TextView
android:id="@+id/deadline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/name"
android:textColor="#fffa6a10"
android:text="(deadline)" />
</RelativeLayout>
</android.support.v7.widget.CardView>
We can also use the Android graphical designer for this.
We’re almost done, we only need to update our activity to add the Adapter and the view holder.
using System;
using System.Collections.Generic;
using Android.App;
using Android.OS;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
namespace RememberIt
{
[Activity(Label = "Things to remember")]
public class RememberListActivity : AppCompatActivity
{
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.RememberList);
// Setup the toolbar
Android.Support.V7.Widget.Toolbar myToolbar = (Android.Support.V7.Widget.Toolbar)FindViewById(Resource.Id.my_toolbar);
SetSupportActionBar(myToolbar);
// Initialize the recycler view
recyclerView = FindViewById<RecyclerView>(Resource.Id.recyclerView);
layoutManager = new LinearLayoutManager(this);
recyclerView.SetLayoutManager(layoutManager);
// Populate the list
PopulateList();
}
public override bool OnOptionsItemSelected(Android.Views.IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_add:
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
public override bool OnCreateOptionsMenu(Android.Views.IMenu menu)
{
MenuInflater.Inflate(Resource.Menu.MainMenu, menu);
return base.OnCreateOptionsMenu(menu);
}
/// <summary>
/// Populates the list.
/// </summary>
void PopulateList()
{
// Let's create some dummy elements
RememberThing thing1 = new RememberThing();
thing1.Name = "Bring the milk";
thing1.Deadline = DateTime.Now.AddMinutes(10);
RememberThing thing2 = new RememberThing();
thing2.Name = "Bring the bread";
thing2.Deadline = DateTime.Now.AddMinutes(20);
List<RememberThing> rememberThings = new List<RememberThing>();
rememberThings.Add(thing1);
rememberThings.Add(thing2);
recyclerView.SetAdapter(new RememberThingsAdapter(rememberThings));
}
/// <summary>
/// The adapter.
/// </summary>
public class RememberThingsAdapter : RecyclerView.Adapter
{
public List<RememberThing> RememberThings { get; set; }
public RememberThingsAdapter(List<RememberThing> rememberThings)
{
RememberThings = rememberThings;
}
/// <summary>
/// The View Holder
/// </summary>
public class RememberThingsViewHolder : RecyclerView.ViewHolder
{
TextView name;
TextView deadline;
public RememberThingsViewHolder(View view) : base(view)
{
name = view.FindViewById<TextView>(Resource.Id.name);
deadline = view.FindViewById<TextView>(Resource.Id.deadline);
}
public void BindViewHolder(RememberThing rememberThing)
{
name.Text = rememberThing.Name;
deadline.Text = rememberThing.Deadline.ToString();
}
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
View view = LayoutInflater.From(parent.Context).Inflate(Resource.Layout.RememberThing, parent, false);
return new RememberThingsViewHolder(view);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
RememberThing rememberThing = RememberThings[position];
(holder as RememberThingsViewHolder).BindViewHolder(rememberThing);
}
public override int ItemCount
{
get
{
return RememberThings.Count;
}
}
}
}
}
Deploy and…

Be able to add manually some “Remember It” elements

For this we need a dialog and to update the activity after pushing CREATE button.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android&quot;
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editText1"
android:hint="Name" />
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:calendarViewShown="false" />
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner" />
</LinearLayout>
view raw ItemCreate.axml hosted with ❤ by GitHub
And finally, update the RememberListActivity.
public override bool OnOptionsItemSelected(Android.Views.IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_add:
CreateNewItem();
return true;
default:
return base.OnOptionsItemSelected(item);
}
}
void CreateNewItem()
{
View dialogView = LayoutInflater.Inflate(Resource.Layout.ItemCreate, null);
// Retrieve the components
EditText name = dialogView.FindViewById<EditText>(Resource.Id.editText1);
DatePicker datePicker = dialogView.FindViewById<DatePicker>(Resource.Id.datePicker1);
TimePicker timePicker = dialogView.FindViewById<TimePicker>(Resource.Id.timePicker1);
// Build the dialog
Android.Support.V7.App.AlertDialog.Builder builder = new Android.Support.V7.App.AlertDialog.Builder(this);
builder.SetPositiveButton("Create", (sender, e) => CommitCreation(name.Text, datePicker, timePicker));
builder.SetNegativeButton("Cancel", (sender, e) => { });
Android.Support.V7.App.AlertDialog dialog = builder.Create();
dialog.SetView(dialogView);
dialog.Show();
}
void CommitCreation(string name, DatePicker datepicker, TimePicker timepicker)
{
RememberThing rememberThing = new RememberThing();
rememberThing.Name = name;
int hours = 0;
int minutes = 0;
int seconds = 0;
// Init values
if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
{
hours = timepicker.Hour;
minutes = timepicker.Minute;
}
else
{
hours = timepicker.CurrentHour.IntValue();
minutes = timepicker.CurrentMinute.IntValue();
}
rememberThing.Deadline = new DateTime(datepicker.DateTime.Year, datepicker.DateTime.Month,
datepicker.DateTime.Day, hours, minutes, seconds);
adapter.RememberThings.Insert(0, rememberThing);
adapter.NotifyItemInserted(0);
}
Deploy and…
Full source code can be found on Github.
See you soon…

Hands on Xamarin Platform Pipeline – Context & Environment Description

If you haven’t read this post yet, please do before reading this one.

Before starting the development, some preparations need to be performed and the main tasks are:

  •  Knowing the application requirements
  • Define the technology stack
  • Install and configure the environment

In our case, for the Operating System, Mac OSX Sierra will be used but there is no big difference between Xamarin on Mac and Xamarin on Windows.

For the mobile application, it will be a simple Android application (Xamarin Traditional Approach or Xamarin Native) and it will be called ‘Remember It’. In the main screen we’ll have a list of things to remember with possibility to add elements and attach an alarm on them, the elements are saved in Azure backend. An authentication will be mandatory before displaying the list.

To get start using Xamarin is pretty easy, following is the description of what I have in my environment:

  • I’ll be using my MSDN Enterprise license to use all the Xamarin Platform, Xamarin Community Edition (or trial mode) can be used to perform to develop and build at least
  • Android SDK (eventually NDK) installed
  • Xamarin components installed: Xamarin IDE and Xamarin.Android (Xamarin installation)
  • Xamarin Profiler and Xamarin Test Recorder
  • For the backend, we’ll use Visual Studio Mobile Center for Identity, Database, Crash reports and Analytics

Hands on Xamarin Platform Pipeline – Introduction

Quality in mobile industry is becoming nowadays something mandatory. Also mobile users are known to be very demanding at the point only 16% of users keep an app after 2 buggy experiences.


Also, studies shown that mobile users use between 5-20 max applications, currently the mobile store size is about 3 billion applications per platform. So how can a developer deliver an application and be on the top 10? This requires of course strong platform and high quality tools.


For those who doesn’t know Xamarin, following a quick information about it:

  • Founded in May 2011, acquired by Microsoft in February 2016
  • Supports Native iOS, Android, Mac and Windows Mobile App development platform
  • Supports C# 6 as development language, initially based on Mono
  • Has same day support and always up to date
  • Application built on Xamarin have native characteristics: Native User Interface, Full SDK Access and Native Performance

And of course, we can’t forget the famous Xamarin quote: “Anything you can do natively you should be able to do with Xamarin.”


Using Xamarin since 2013 and being a user of other mobile development approaches (Native development using Android Java, iOS Objective-c or Swift, hybride architectures with Ionic…), in my point of view Xamarin is the best choice that helps deliver high quality cross platform mobile applications.

Xamarin currently covers the complete DevOps pipeline:
In the following blog posts I expect to give a practical guidance and tutorials in order to have a mobile application that uses all the Xamarin tools and to have Continuous integration and Continuous Delivery in place.

We’ll start by Context & Environment Description then the Develop-Test-Build-Distribute-Monitor plan will be followed.

Develop

Let’s start by an offline application
Add authentication using Azure Active Directory
Let’s explore some nice features of Xamarin Studio 6
Exploring Visual Studio Mobile Center
Add Facebook authentication

Build