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.

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.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.Android – 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 Android multimedia 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

Before starting development on your application using MediaPlayer, make sure your manifest has the appropriate declarations to allow use of related features.

Internet Permission – If you are using MediaPlayer to stream network-based content, your application must request network access.

Wake Lock Permission – If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode()methods, you must request this permission.

One of the most important components of the media framework is the MediaPlayer class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:

  • Local resources
  • Internal URIs, such as one you might obtain from a Content Resolver
  • External URLs (streaming)

Playing Audio with MediaPlayer – Using the built-in MediaPlayer class to play audio, including local audio files and streamed audio files with the AudioTrackclass.

Recording Audio – Using the built-in MediaRecorder class to record audio.

Working with Audio Notifications – Using audio notifications to create well-behaved applications that respond correctly to events (such as incoming phone calls) by suspending or canceling their audio outputs.

Working with Low-Level Audio – Playing audio using the AudioTrack class by writing directly to memory buffers. Recording audio using the AudioRecord class and reading directly from memory buffers.

In addition to stopping the MediaPlayer you want to call the release() method on the object when you are done with the audio to free up resources.

Starting and Stopping Audio

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

Xamarin.Android – Creating Lists and Opening the Browser

The ListView Control

aa1cTrKw7PEdW3

Displaying a list is one of the most common design patterns used in mobile applications. This makes the ListView control one of the most important design elements. In this lesson we will look at how to create a list of items in our app using the ListView control.

There is a great tutorial that digs in deeper with ListView controls and setting up custom adapters and layouts here: http://www.vogella.com/tutorials/AndroidListView/article.html

A ListView consists of the following parts:

Rows – The visible representation of the data in the list.

Adapter – A non-visual class that binds the data source to the list view.

Fast Scrolling – A handle that lets the user scroll the length of the list.

Section Index – A user interface element that floats over the scrolling rows to indicate where in the list the current rows are located.

There is a great tutorial that digs in deeper with ListView controls and setting up custom adapters and layouts here: https://developer.xamarin.com/guides/xamarin-forms/user-interface/listview/interactivity/

The primary classes:

ListView – user interface element that displays a scrollable collection of rows. On phones it usually uses up the entire screen (in which case, the ListActivity class can be used) or it could be part of a larger layout on phones or tablet devices.

View – a View in Android can be any user interface element, but in the context of a ListView it requires a View to be supplied for each row.

BaseAdapter – Base class for Adapter implementations to bind a ListView to a data source.

ArrayAdapter – Built-in Adapter class that binds an array of strings to a ListView for display. The generic ArrayAdapter<T>does the same for other types.

CursorAdapter – Use CursorAdapter or SimpleCursorAdapter to display data based on an SQLite query.

 Android includes built-in ListActivity and ArrayAdapter classes that you can use without defining any custom layout XML or code. The ListActivity class automatically creates a ListView and exposes a ListAdapter property to supply the row views to display via an adapter. The built-in adapters take a view resource ID as a parameter that gets used for each row. You can use built-in resources such as those in Android.Resource.Layout so you don’t need to write your own.

There is a lot of opportunity for customizing the appearance of the ListView control. Want to learn more? Check out this section – https://developer.xamarin.com/guides/android/user_interface/working_with_listviews_and_adapters/part_3_-_customizing_a_listview’s_appearance/

Opening the Browser

Android phones have a built-in browser with an intent filter that accepts the intent requests from other apps. To use this you have to have a URI (Uniform Resource Identifier) which is a string that identifies the resource of the Web site.

You may already be familiar with the term URL (Unform Resource Locator) – a URI is a URL with additional information that is needed for gaining access to resources required for posting the page.

We can use what we’ve previously learned about Intents to open the browser window.

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

Top 10 Reasons You Won’t Get The Job – Part 2

Picking up with my top 5 from my previous list.

5 – Don’t Lie

It seems like it should be a given but don’t lie on your resume or to your interviewer.  There are plenty of people that are paid to follow up on details and you will be caught out. Not only will you be fired if it finds out that you lied during your interview (or not hired at all).  But you will most likely be blacklisted from applying with that company again in the future, which can deeply hurt your career advancement. There is also the problem with people who work in small circles. One mistake like this and you may find that every HR person in town has heard about what happened at XYZ company, because everyone in HR talks to each other.  Don’t fall into this situation and keep everything on your resume truthful!

4 – You Give Up

When an interviewer gives you a problem to work through during your interview they are looking for a few key things.  First, what is your thought process like when you are faced with a problem?  The best thing you can do in this situation is start talking through the problem aloud, stating your logic and reasoning.  You’re not really talking to the interviewer, just vocalizing your thoughts.  This way the interviewer can hear about what assumptions you are making and possibly jump in with a hint or bit of clarifying information.  We aren’t mind readers so if you’re just staring at the board, stuck and confused, we don’t know what went wrong if you aren’t talking.  The #1 problem that then arises is that you give up on the problem. This is the second thing that your interviewer wants to know about – your character.  What do you do when faced with adversity?  Do you plunge ahead with a potentially wrong answer?  Do you try different angles?  Do you search for resources?  Or do you do the one thing that will ensure they will pass on giving you an offer – you quit working. Even if you are stuck and confused, keep working on the problem from different angles until they stop you.  Never quit.

3 – You Don’t Ask Questions

Every interview article you’ve ever read has probably told you that you need to ask questions during your interview and they all say it because it is true! Asking questions shows that you are interested in the position, want to know more about the company and are excited to work there. Always ask follow up questions during interviews if you want more information on something that the interviewer has discussed. It should not be a one-sided conversation.  Remember that interviews are just as much about you finding a good employer you want to work for as it is about them finding a good fit for their company.  Ask the questions that you need to ask to ensure that you can make an informed decision.  Always have a question ready in your back pocket for the end of the interview when they ask: “Do you have any other questions?”.  Don’t just grab your things and shake their hand.  Show that you are interested by having something to talk about.  I will note a caveat here – avoid bringing up salary, benefits, vacation days or other “sensitive” compensation items that you haven’t discussed yet.  This will make the interviewer a little uncomfortable since they are not prepared to talk about this yet. Keep your questions focused on the day-to-day or responsibilities of the position, things you saw during your tour, technologies, or what the company is currently working on.

2 – You Don’t Apply What You’ve Learned During The Day

This item doesn’t apply to all companies but you could rephrase it to say “You Don’t Apply What You’ve Learned In Past Interviews” and it would work for everyone.  Some companies do multi-part interviews over the course of a day.  You may come in for the first round and if you make the cut, move on to the second round in the same afternoon.  Doing well there may mean a deeper hands-on interview with an engineer a few hours later.  These interviews are very stressful as you have to be on your game all day but they also give you an unparalleled look at the inside of the business. The key thing here is to remember to apply what you are learning as you move through the rounds.  Each interviewer will provide you with feedback or areas for improvement.  If these are things you can change right now, you should be showing that you are listening to feedback and trying to implement and learn from it. Likewise for companies that do a phone interview and then an in-person interview.  If your phone interviewer has given you feedback that you can apply in the in-person interview, be sure you are showing that you are open to feedback and willing to improve.

1 – You Make Assumptions

Don’t assume that you understand what the interviewer is talking about.  Clarify what the interviewer is really asking you so you can be sure that you are answering the question.  I’ve seen interviewees go off on a tangent while working on a problem for 10 minutes only to find that they didn’t understand the problem they were trying to solve. My recommendation is, when you get a whiteboard question, the first thing you should do is write the question on the board. This way, the interviewer can immediately see if you didn’t heard them correctly.  You can also ask them to verify if that is the question they have posed.  Then start with clarifying questions about the problem so you understand what you are solving and are not making assumptions. Write down key information on the board as well.  Once you feel you have a handle on it, start pseudo-coding the problem before you actually code it to work out any logic issues first.

Remember, interviews ultimately want to see you do your best so they can find out if you are the best candidate for the job.  They are not there to intimidate you or make you nervous.  Most will try to help you out if you are providing them with the means to do so.  Relax, try to have fun and learn as much as you can from each interview.  Sometimes it will take a few before you get the job but with each try, you will have more information from which to improve.