Category Archives: Programming

Xamarin Android – Using ListView Controls with Shared Preferences

I have previously demoed how to work with the ListView control on the Xamarin Android platform but this post is going to be a little more advanced.  If you are new and need to get started with the basics of the ListView control, I suggest you start with this post. Once you have the basics down, you can also check out how to make your own custom ListView Adapters in the two-part tutorial that starts with this post.

This tutorial also assumes you know how to use some of the built-in storage for your Android device. If you’re not sure how to access things like Shared Preferences, check out this tutorial first!

If you’re up to speed and ready to go, let’s check out some advanced ListView functions!

Setting up a ListView

I’ve shown you a couple of different ways in the past to setup a ListView but here is some review.  You can basically choose to either put a ListView control on the form (by getting it from the toolbox) or you can change your Activity type to a ListActivity.  A ListActivity is going to inherit a ListView control all on it’s own so you can just access the ListAdapter directly and provide whatever data items you want to show.

Shared Preferences

The Shared Preferences area of the Android system allows you to store data about your application as key/value pairs. The data you can store are all simple types such as bool, float, int, string and long. The data that you save in Shared Preferences is only for your app and it cannot be accessed by other apps on the device. However, the data is persistent which means it is saved to the phone and you can access it or modify it at any time from within your app. This makes for a handy place you can quickly store information that you want to use later.

Writing to Shared Preferences

Writing to the Shared Preferences data area is pretty simple.  We access it through an interface called ISharedPreferences. This interface requires the Android.Content using statement to be added to your project. When you first start using Shared Preferences you have to initialize a “file” for your app to store the key/value pairs inside.  It looks something like:

ISharedPreferences prefs = Application.Context.GetSharedPreferences("USER_DATA", FileCreationMode.Private);

Then you can setup your editor

ISharedPreferencesEditor editor = prefs.Edit();

and add in all of the key/value pairs you want

editor.PutString("item1", "Steak");

When you’re done, you apply the edits

editor.Apply();

Reading from Shared Preferences

Reading from the Shared Preferences file isn’t really any more difficult than writing to it. You use the GetString(), GetInt(), etc…methods that correspond to the types of data you have stored. By providing the right key name, you get your value returned. This will look something like:

prefs.GetString("item1", null);

I hope you have enjoying this quick tutorial on using ListViews with SharedPreferences! If you want to get a walk-through of how to put this together, check out the video on YouTube below.  You can also get some sample code from my Github: https://github.com/rhysma/XamarinAndroidListViewSP

Using WebView to display HTML in Android Xamarin Apps

Using Web View

Often in our apps we want to be able to deliver web content that we already have or maybe just a web page as part of the client application. This is helpful especailly if we already have this content available as HTML and we don’t want to have to re-create it in our app format or create new views. Xamarin makes this easy with the WebView class. WebView allows you to create your own window for viewing web pages (or even develop a complete browser).

A common scenario in which using WebView is helpful is when you want to provide information in your application that you might need to update, such as an end-user agreement or a user guide. Within your Android application, you can create an Activity that contains a WebView, then use that to display your document that’s hosted online.

Using WebView in your application is very easy. It requires the Android.Webkit library to be added in and then with a few lines of code you can be up and running!

myWebView = FindViewById<WebView>(Resource.Id.webView1);
 myWebView.SetWebViewClient(new WebViewClient());
 myWebView.Settings.JavaScriptEnabled = true;
 //myWebView.LoadUrl("http://rhysma.github.io");

Enabling JavaScript on WebView

If the web page you plan to load in your WebView use JavaScript, you must enable JavaScript for your WebView. Once JavaScript is enabled, you can also create interfaces between your application code and your JavaScript code. JavaScript is disabled in a WebView by default.

webSettings.setJavaScriptEnabled(true);

Handling Page Navigation

One of the trickiest parts of using WebView is being able to manage the page navigation. When the user clicks a link from a web page in your WebView, the default behavior is for Android to launch an application that handles URLs. Usually, the default web browser opens and loads the destination URL. This is obviously not what we want to have happen. WebView does keep track of page navigation history so we can allow the user to move backwards and forwards while still retaining them in the WebView frame of our app and not opening the browser.

Ultimately we can control this by overriding the OnBackPressed method and using the WebView’s history instead. When your WebView overrides URL loading, it automatically accumulates a history of visited web pages. You can navigate backward and forward through the history with GoBack() and GoForward().

public override void OnBackPressed()
 {
 myWebView.GoBack();
 }

Loading Local Content

Sometimes we have HTML pages that we want to load in but they aren’t necessarily hosted URLs.  We can use the same concepts to load in local HTML pages in a Web View.  This can be helpful if you already have the HTML content (like the end-user agreement example from the start) and want to render it out to your user as-is.

For a complete walk-through of these concepts check out my video below.  You can also get a complete download of the project on my Github.

Using HTML to Format Text in Xamarin

I have to give props to Trevor Hart on this idea – he sent a message to a dev group I am in that said: “Hello fellow humans, have you ever used Xamarin and thought “Wow, how in the world is HTML easier to format text with than Android?”, well good news, you can tell android to act like an html interpreter so that you can do all your nice fancy styling in an html file, then just load it into a text view for Android. All you have to do is use the asset manager to get a stream to the html file, read from the stream and store it in a string, call fromHtml and pass the string, and pass that to setText for a text view. It’s pretty sweet actually.”

So I got to thinking – that IS actually pretty sweet!

As the landscape of web and mobile development gets more intertwined and complex, it is becoming very important to deliver a solid and consistent experience among all of the contexts that your content is viewed.  What better way to do that than to deliver a mobile-first, responsive, and adaptive experience we know and love in HTML while still leveraging the .NET power given through Xamarin.

Different from Hybrid Apps?

In the mobile development world the term “hybrid app” typically refers to an application that presents some (or all) of its screens as HTML pages inside a hosted web viewer control.

There are some development environments that let you build your mobile app entirely in HTML and Javascript, however those apps can suffer from performance problems when trying to accomplish complex processing or UI effects and are also limited in the platform features they can access.

Xamarin offers the best of both worlds, especially when utilizing the Razor HTML templating engine. With Xamarin you have the flexibility to build cross-platform templated HTML views that use Javascript and CSS, but also have complete access to the underlying platform APIs and fast processing using C#.

Let’s walk through how to do this so you can see how it works!

The HTML/CSS

So to start, I put together a simple and clean HTML layout that I wanted to use to demo this idea.   Here is the layout I am working with:

Download for yourself – HTML

Create the Xamarin Project

As usual, create an Android Xamarin project to get started. This video will walk you through how read in the HTML file in your Xamarin Android project.

 Final Thoughts

So I’m sure you can see, as I did, how great of a tool this is.  Often we have text that we want to be able to present to the user in a formatted way and using the editor when making Xamarin forms is pretty painful for this kind of thing.

Custom ListView Adapters with SQLite – Part 1

In my previous post I talked about how to create SQLite databases in our Android.Xamarin applications. I wanted to show you how to do some more robust things in your apps with the power of databases but while I was creating that plan, I realized that while I had talked about how to use the ListView control in the past, I hadn’t really worked on how to do ListView adapters other than the simple ArrayAdapter class. Let’s remedy that right away!

Creating Custom ListAdapters

The basic ArrayAdapter class is great but if we really want to get some power behind our ListViews then we want to create a ListAdapter that will give us the ability to customize the view. When we use a ListAdapter we have to override the base class BaseAdapter and fill in the information on behavior and display that we want.

There are two properties that we must override in BaseAdapter:

  • Count – To tell the control how many rows are in the data.
  • this[int] indexer – To return the data associated with a particular row number.

There are two methods as well:

  • GetView – To return a View for each row, populated with data. This method has a parameter for the ListView to pass in an existing, unused row for re-use.
  • GetItemId – Return a row identifier (typically the row number, although it can be any long value that you like).

The most important part is the GetView method. GetView allows us to customize how we want to display each row inside of the ListView and also handles how rows are re-used in the View. When displaying hundreds or thousands of rows, however, it would be a waste of memory to create hundreds or thousands of View objects when only eight fit on the screen at a time. To avoid this situation, when a row disappears from the screen its view is placed in a queue for re-use. As the user scrolls, the ListView calls GetView to request new views to display – if available it passes an unused view in the convertView parameter. If this value is null then your code should create a new view instance, otherwise you can re-set the properties of that object and re-use it. Pretty cool, right?

A word of warning – if you don’t handle row re-use you will run the risk of your app chewing up all of the device memory and then crashing. Custom adapter implementations should always re-use the convertView object before creating new views to ensure they do not run out of memory when displaying long lists.

Context Menus

A context menu is a type of pop-up menu that is attached to a particular view. In the example I am doing for you today, the menu pops up on top of the View and allows you to setup different menu items that you can then attach functionality to. In the case of the app I am building in this demonstration, we are managing the names and phone numbers of contacts we wish to store.  If we should want to edit or delete those contacts, we can select them from our list and choose the appropriate action from the context menu.

In this video I will walk you through creating your custom ListAdapter and setup a Context Menu for your list. Stay tuned for Part 2 on this topic where we will use the context menu to call some SQLite database functionality.

Android.Xamarin – Getting Started with SQLite

I know I have previously written about how to store data on your Android device using the Xamarin platform but there are a few different methods for data storage that you want to consider based on your app’s needs. Using the SharedPreferences section of the device is not always appropriate or feasible and we need a more robust option for storing data.

Why Use a Database?

There are a number of advantages to using an SQL database in your mobile app:

  • SQL databases allow efficient storage of structured data.
  • Specific data can be extracted with complex queries.
  • Query results can be sorted.
  • Query results can be aggregated.
  • Developers with existing database skills can utilize their knowledge to design the database and data access code.
  • The data model from the server component of a connected application may be re-used (in whole or in part) in the mobile application.

I would also add that while many developers think that using a SQL server is a more robust option, we have to think about app performance and reliability when the cellular connection is bad or the server is unavailable. There are also a lot of security implications of using synchonized and decentrialized storage and we want to be sure that we are accessing and transmitting data securely, which is not something that new developers really think about.  By storing the data on the phone we eliminate some of the security risks we could be facing by moving that data to a server.

What is SQLite?

SQLite is an in-process library that implements a self-contained, serverless, zero-configuration, transactional SQL database engine. The code for SQLite is in the public domain and is thus free for use for any purpose, commercial or private. You can learn more about SQLite here.

One of the main benefits of using SQLite for Android apps is that the SQLite engine has been adopted by Google for the mobile platform.  It is also very easy to use with the SQLite .NET tools that are available to us through the Xamarin platform.

SQLite is well suited to cross-platform mobile development because:

  • The database engine is small, fast and easily portable.
  • A database is stored in a single file, which is easy to manage on mobile devices.
  • The file format is easy to use across platforms: whether 32- or 64-bit, and big- or little-endian systems.
  • It implements most of the SQL92 standard.

It is very easy to get started using SQLite on your Android apps.  Here is my video that walks you through setting up your project and doing some basic data operations so you can get started using databases in your apps right now.

Xamarin – Using Web Services

In this lesson will we be discussing how to invoke web services from your Xamarin iOS and Android applications. There are a few different ways that these applications can connect with web service technologies. The Xamarin platform supports consuming different web service technologies, and includes in-built and third-party support for consuming RESTful, ASMX, and Windows Communication Foundation (WCF) services.

What is REST?

Representational State Transfer (REST) is an architectural style for building web services. REST requests are made over HTTP using the same HTTP verbs that web browsers use to retrieve web pages and to send data to servers. The verbs are:

  • GET – this operation is used to retrieve data from the web service.
  • POST – this operation is used to create a new item of data on the web service.
  • PUT – this operation is used to update an item of data on the web service.
  • PATCH – this operation is used to update an item of data on the web service by describing a set of instructions about how the item should be modified. This verb is not used in the sample application.
  • DELETE – this operation is used to delete an item of data on the web service.

Web service APIs that adhere to REST are called RESTful APIs, and are defined using:

  • A base URI.
  • HTTP methods, such as GET, POST, PUT, PATCH, or DELETE.
  • A media type for the data, such as JavaScript Object Notation (JSON).

The simplicity of REST has helped make it the primary method for accessing web services in mobile applications.

What is SOAP?

SOAP (Single Object Access Protocol) is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on Extensible Markup Language (XML) for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) and Simple Mail Transfer Protocol (SMTP), for message negotiation and transmission.

ASP.NET Web Service (ASMX)

ASMX provides the ability to build web services that send messages using the Simple Object Access Protocol (SOAP). SOAP is a platform-independent and language-independent protocol for building and accessing web services. Consumers of an ASMX service do not need to know anything about the platform, object model, or programming language used to implement the service. They only need to understand how to send and receive SOAP messages.

A SOAP message is an XML document containing the following elements:

  • A root element named Envelope that identifies the XML document as a SOAP message.
  • An optional Header element that contains application-specific information such as authentication data. If the Headerelement is present it must be the first child element of the Envelope element.
  • A required Body element that contains the SOAP message intended for the recipient.
  • An optional Fault element that’s used to indicate error messages. If the Fault element is present, it must be a child element of the Body element.

SOAP can operate over many transport protocols, including HTTP, SMTP, TCP, and UDP. However, an ASMX service can only operate over HTTP. The Xamarin platform supports standard SOAP 1.1 implementations over HTTP, and this includes support for many of the standard ASMX service configurations.

Generating a Proxy

proxy must be generated in order to consume an ASMX service, which allows the application to connect to the service. The proxy is constructed by consuming service metadata that defines the methods and associated service configuration. This metadata is exposed as a Web Services Description Language (WSDL) document that is generated by the web service. The proxy is built by using Xamarin Studio or Visual Studio to add a web reference for the web service to the platform-specific projects.

The web service URL can either be a hosted remote source or local file system resource accessible via the file:/// path prefix, for example:

hzIS2AfGVax3HM

This generates the proxy in the Web or Service References folder of the project. Since a proxy is generated code, it should not be modified.

Windows Communication Foundation (WCF)

WCF is Microsoft’s unified framework for building service-oriented applications. It enables developers to build secure, reliable, transacted, and interoperable distributed applications.

WCF describes a service with a variety of different contracts which include the following:

  • Data contracts – define the data structures that form the basis for the content within a message.
  • Message contracts – compose messages from existing data contracts.
  • Fault contracts – allow custom SOAP faults to be specified.
  • Service contracts – specify the operations that services support and the messages required for interacting with each operation. They also specify any custom fault behavior that can be associated with operations on each service.

There are differences between ASP.NET Web Services (ASMX) and WCF, but it is important to understand that WCF supports the same capabilities that ASMX provides – SOAP messages over HTTP.

In general, the Xamarin platform supports the same client-side subset of WCF that ships with the Silverlight runtime. This includes the most common encoding and protocol implementations of WCF — text-encoded SOAP messages over the HTTP transport protocol using the BasicHttpBinding class. In addition, WCF support requires the use of tools only available in a Windows environment to generate the proxy.

Considerations for web services

When creating apps that require a web service it is important to note that the app will require constant connectivity via the mobile connection or wifi to work. This can cause some problems when users try to use your app in areas of bad connectivity or poor reception. We will look at how to check for both mobile and wifi connectivity in the demo.

In the video below I show you how to connect to a web service using an iOS project but if you are working with Android Xamarin projects, the code and steps are going to be exactly the same. Bonus!

This video will show you how to check for a Wi-Fi and Mobile Internet connections in your Android and iOS applications written with Xamarin.  Once we have checked for network connectivity, I will show you how to connect to a web service using the Windows Communication Foundation (WCF).

Here is the link to the W3Schools web service used in this tutorial – http://www.w3schools.com/xml/tempconvert.asmx

Xamarin.iOS- Storing Data

Xamarin.iOS can use the same System.IO classes to work with files and directories in iOS that you would use in any .NET application. However, despite the familiar classes and methods, iOS implements some restrictions on the files that can be created or accessed and also provides special features for certain directories. This article outlines these restrictions and features, and demonstrates how file access works in a Xamarin.iOS application.

Locations of Persistent Data

iOS provides several options for saving application data based on the specific needs of the app. Some apps require private storage while others need to share data between apps.

There are five different places to store data:

  • Shared Preferences – Stores data in key/value pairs
  • Internal Storage – Stores private data in the memory of the device
  • External Storage – Stores data, which can be available to other apps on shared external storage
  • SQLite Databases – Stores structured data in a private database
  • Network Connection – Stores data on a Web server

iOS imposes some restrictions on what an application can do with the file system to preserve the security of an application’s data, and to protect users from malignant apps. These restrictions are part of the Application Sandbox – a set of rules that limits an application’s access to files, preferences, network resources, hardware, etc. An application is limited to reading and writing files within its home directory (installed location); it cannot access another application’s files.

iOS also has some file system-specific features: certain directories require special treatment with respect to backups and upgrades, and applications can also share files via iTunes

This video will walk you through creating an app that stores information to a text file on the device. We will store some information and then retrieve it for display using  the .NET System.IO classes for file system operations on iOS.

Xamarin.iOS – Adding Audio

Adding audio to your applications can take on many forms. This could be a sound-effect for a game, audio that is played on demand, or in the form of a podcast or audiobook.

The iOS framework includes support for playing variety of common media types, so that you can easily integrate audio, video and images into your applications. You can play audio or video from media files stored in your application’s resources (raw resources), from standalone files in the filesystem, or from a data stream arriving over a network connection.

Setting Your App Up for Audio

The AVAudioPlayer is used to playback audio data from either memory or a file. Apple recommends using this class to play audio in your app unless you are doing network streaming or require low latency audio I/O.

You can use the AVAudioPlayer to do the following:

  • Play sounds of any duration with optional looping.
  • Play multiple sounds at the same time with optional synchronization.
  • Control volume, playback rate and stereo positioning for each sounds playing.
  • Support features such as fast forward or rewind.
  • Obtain playback level metering data.

AVAudioPlayer supports sounds in any audio format provided by iOS, tvOS and OS X such as .aif, .wav or .mp3.

Starting and Stopping Audio

This video will show you how to use the AVAudioPlayer class to start and stop MP3 audio in your Xamarin iOS app.

Here is the link to the AudioManager class that is used in this video – https://dl.dropboxusercontent.com/u/13327672/295%20files/AudioManager.cs

Xamarin.iOS – Creating Lists and Opening the Browser

The Tables UITableViewController

Displaying a list is one of the most common design patterns used in mobile applications. Tables are one of the single most important controls in iOS applications. It’s hard to find an application that doesn’t use tables in some form. Tables in iOS are highly customizable and wrap a lot of functionality that we get for free.

aa1cTrKw7PEdW3

The source for the data displayed in the TableView can come from objects such as arrays or Lists. You can also bind to a data source such as a database table.

In order to determine what should happen when a row is clicked, you can use the RowSelected event.

A UITableView can have a ‘grouped’ or ‘plain’ style, and consists of the following parts:

Ci17gCS_PHIUfe

There is a lot of functionality to make your TableViews really pop in your application.

  • Swipe to delete individual cells.
  • Entering Edit mode to reveal delete buttons on each row
  • Entering Edit mode to reveal re-ordering handles.
  • Inserting new cells (with animation).

PipC_AnZwUmL-5

The primary classes used to display table views are shown here

In this tutorial, we will be using UITableViewSource – Xamarin.iOS-exclusive abstract class that provides all the methods required to display a table, including row count, returning a cell view for each row, handling row selection and many other optional features. Youmust subclass this to get a UITableView working.

Opening the Browser

When we want to perform actions using another app on the device, we can do a SharedApplication call. This is part of the UIApplication class, which holds all of the central administrative properties for any application running on iOS (more here: https://developer.xamarin.com/api/type/UIKit.UIApplication/)

Here is the video walk-through for this lesson that shows how to setup a TableView and launch the browser window.

Xamarin.Android – Storing Data

An Android app typically requests data and then modifies that data to produce a result throughout multiple activities. With programs you have written so far, the values entered did not persist beyond the Activity in which they were created. The data was lost because it was being stored in RAM which is cleared each time the app is closed. To create persistent data that can be accessed over and over, Android apps can save data on the device’s drive or other storage media such as a memory card. This lesson will show you how to store data that your app can then retrieve and use.

Locations of Persistent Data

Android provides several options for saving application data based on the specific needs of the app. Some apps require private storage while others need to share data between apps.

There are five different places to store data:

  • Shared Preferences – Stores data in key/value pairs
  • Internal Storage – Stores private data in the memory of the device
  • External Storage – Stores data, which can be available to other apps on shared external storage
  • SQLite Databases – Stores structured data in a private database
  • Network Connection – Stores data on a Web server

Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.

In addition to the Android system storage locations, Xamarin apps also have Application.Current.Properties which is implemented in Xamarin.Forms which allows you to store simple Key-Value pairs of data as well. The Properties dictionary is saved to the device automatically. Data added to the dictionary will be available when the application returns from the background or even after it is restarted.

Xamarin.Forms 1.4 introduced an additional method on the Application class – SavePropertiesAsync() – which can be called to proactively persist the Properties dictionary. This is to allow you to save properties after important updates rather than risk them not getting serialized out due to a crash or being killed by the OS.

This video will walk you through creating an app that stores information using the Shared Preferences. We will store data using an Editor and retrieve it. Retrieving Android data is just about as easy as saving it when you are working with SharedPreferences. The difference is that you do not need to setup an Editor in order to read data that has already been stored.