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.
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:
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:
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
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!
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()
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.
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.
Let’s walk through how to do this so you can see how it works!
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:
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.
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.
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.
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.
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.
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.
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
A 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:
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).