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 –

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


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:

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:

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 –’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.

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

Over the years, I’ve done quite a bit of hiring and the things that people do that negatively impact their chances of getting a job are sometimes pretty astounding. I understand that you are nervous – it’s OK, we’re all human. However, there are some key mistakes that I’ve seen over and over again that I have compiled into my Top 10 Reasons You Won’t Get The Job.  Since these are kind of long, here are the first five:

10 – You Didn’t Prepare

If you have gone through the trouble of finding the job posting, writing a cover letter, submitting all of your documents, and passing a phone interview why would you not prepare for the actual in-person interview?! Before you step into that room you should have done you research on the company.  Find out their mission statement, goals, strategic objectives, position in the industry, and key operating information.  What have been their latest successes? Failures? Find out everything you can about the position.  Use networking tools like LinkedIn and GlassDoor to talk to people that already work there about the job duties, supervisor, and work environment.  You should also find out how this company likes to interview.  Is it going to just be you and a few HR and technical people?  Does this company like to bring in panels of 10? In this age of information there is absolutely no reason to go into these situations blind. There is also no bigger turn off to a hiring manager than to have you ask questions for things that would’ve been easily answered with a small amount of research.  You need to be just as interested in working for the company as you want them to be interested in hiring you.

9 – You Didn’t Sleep

So you spent the night before your interview tossing and turning in bed.  By getting yourself all worked-up and nervous, you have cheated yourself out of the rest that you needed to perform well in your interview and make a good first impression. If you have followed #10 then you should be prepared and feel confident that you can walk into your interview and have the knowledge to succeed.  If you are nervous, it’s OK!  Just take the steps needed to relax and get some sleep.  A hot shower, herbal tea, favorite movie – whatever it takes.

8 – You Show Up Late

You cannot believe the number of people I’ve had show up late to an interview! Not only does this show that you have problems with your organization skills, but it could also means that you now lack the time with your interviewer to demonstrate your skills.  Being late also means that you may become more nervous and flustered.  As if showing up late could ruin a first impression any further than now wasting the interviewer’s time with a poor interview.  Look, those of us on the hiring side of the desk understand that everyone is human.  If you are having a completely hectic day and have been faced with a flat tire, unexpected babysitter problems, or another situation that means you cannot perform at your best – call us before your interview and reschedule.  It is highly unlikely that we’re going to say no.  We want you to show us your best!

7 – You Give One Word Answers

No matter what is going on in your interview, never give one word answers. Even if the question could be answered with a yes or no, find a way to provide more detail or insight.  For example:

Interviewer: I see you worked at XYZ company for 4 years?

You: Yes


Try phrasing things like this:

Interviewer: I see you worked at XYZ company for 4 years?

You: Yes, I started in 2010 and held two job titles during my time there. I primarily worked with ABC technology during my time there.

See the difference? This way you are providing more insight into your skills and giving more conversational answers.

6 – You Lack Details

Like the above, you need to be able to articulate the answers to questions and help the interviewer see why you are the best candidate.  Show your problem solving approach and don’t be afraid to think out loud when given hands-on problems or puzzles. Demonstrate how this job relates to your strengths and connect all of the dots for the interviewer so they can have confidence in choosing you for the job.


This wraps up today’s list.  Check out the final 5 

Taking Some Professional Advice

These days there probably isn’t a field that wouldn’t list “communications” as a critical skill needed for successful candidates, but I’ve found that this is even more important in the field of computer science.  Why?  Programmers don’t like people – even themselves.

Talking about yourself is hard. Too much and people think you’re a motormouth, too little and people wonder “why is he so quiet?”. Mentioning your accomplishments can get you marked as a braggart and never talking about them can make you seem like a loser.  Where is the happy medium? Learning to talk about yourself in a self-effacing manner is not only important for interpersonal communication, but it is critical to your success in your career.

One of the best pieces of advice came to me during one of my first jobs out of college.  My boss would regularly walk around the office, talk about how things were going, maybe ask you about your weekend.  He almost always started with the same question: “What have you been working on at home?”.

I remember being surprised and confused by this question.  Why would my boss want to know what I worked on at home?  Was he implying that I should’ve been researching work issues at home on the weekends? I hadn’t really been working on anything on the side.  I was pretty overwhelmed at work with all of the new things I was learning.  I almost felt like I would be wasting my time on things that had nothing to do with my work. After a few months I finally got up the nerve to ask what he meant by this question. What was the expectation?

The advice he gave me is this – ALWAYS have something to tell me.

I started picking up side projects so I would have something to talk to him about.  Little freelance projects that did or did not pay, fun applications and websites that I wanted to write.  I learned so much, so fast. I picked up Python and learned to write little applications and connect to websites, I wrote a web-app for a new business in England that landed me a gig I still work on (5 years later), I picked up C++ and started working on games, I cracked my head on my first Android application. Whatever interested me or sounded fun, I spent some time on.  Many of my personal projects never got finished or were abandoned, but what I had learned stuck with me.

During my time there, I almost always had a side-project going and I always had something to tell my boss about when he came around.  Sometimes he would nod thoughtfully and smile, other times he would give me some pointers or direct me to something I should read.  In a way, my work I was doing outside of the job helped me connect with my boss better than my actual work performance.  He would stop by and ask me how the project we discussed last week was going and he became a mentor I could talk to when I was really stuck. When I decided to move on, he wrote me one of the best recommendations I could ever ask for and I will never forget that encouragement.

I still do side-projects and freelance work today.  Most of my projects are from repeats, referrals, and word-of-mouth and I don’t really have to go looking for them anymore. Learning to talk about myself has also allowed me grow my communication skills and learn to speak with people that I would once be intimidated by as well as communicate about technical details and programming in a way that you can never really master in school. Whatever you’re doing right now, find the time to start working on side projects. Don’t wait for someone to tell you what to do.  Employers want initiative and passion – show them you have what they need and you’ll surprise your boss, clients, and yourself.

Caught Up in the Details

Lately, I’ve been trying to really home-in on some of the problems that I see many of my students going through that holds them back from their learning and programming goals.  Today I want to talk about “the details”.

Computer Science, like many fields, is one that enjoys details.  We thrive on it actually, digging into problems, exploring the minutia, and giving everything an acronym. But I start to think how unhelpful this attitude is to students.  Learning to program well requires the introduction of the following all at once:

  • Terminology
  • Basic concepts of programming
  • Acronyms
  • Development software / IDEs
  • Foundational knowledge in computing
  • Coding standards
  • Documentation
  • Requirements gathering
  • Syntax for the language they are studying

You can probably tell this is an overwhelming list.  I actually could add a few more items but typically, this is what is covered in the first few WEEKS of an introductory computer programming course.  I start to ask myself why.  Why are we so caught up in all of these details?  Why is it so important to impart the skills of documenting or making sure they can understand a bit from a byte when they are first starting out?

It seems to me we would be doing a students a great service if we tried to remove some of these roadblocks to their learning and actually just taught them how to program. We don’t teach people how to drive cars by making them learn how to fix one.   No one ever learned how to write by studying the history of penmanship. Some topics are better left for later when the student has a grasp of the language, then we can go back and make sure that they understand what is going on under the hood.

So today, for all of my students, I would recommend the following – put down the details and focus on the programming.  Really dig into the whys and hows of your current language and don’t worry about all of the peripheral knowledge that you can gain over time.  Slim down your list to:

  • One programming language (of course, I think C# is the best)
  • One IDE – Visual Studio really cannot be beat
  • A simple set of challenges or projects you want to accomplish

You will make far more progress in learning how to program if you narrow your focus towards a goal that can be stated easily such as “A program that can convert temperatures from Fahrenheit to Celsius” or “A program that lets me enter and search my DVD titles”.  Not only will you find that you have more motivation when you are focused on completing a particular project, but you will learn a lot more about your programming language by solving the challenges that will be held within.

If you haven’t checked out my learning course for C# yet, now is a good time to get started – learn more here.

Object Independant Serialization C#.NET

Creating and storing serialized objects in a database is a fairly easy task.  However, the problem comes when you have created serialized objects with one application (or version of an application) and want to deserialize and use them with another.  Usually the error that you get is:

Unable to find assembly 'MyAssembly; Version=1.0.3463.18923;
Culture=neutral; PublicKeyToken=40e3171cc8066fe6'.


Well the issue here is the objects that have been Serialized have a formatter transmits the information required to create an instance of an object of the correct type and version. This information generally includes the full type name and assembly name of the object. The assembly name includes the name, version, and strong name hash of the assembly.  What this ultimately means is that your serialized object data is now tied to the assembly and version that created it.

By default the deserialization process uses this formatter information to recreate the object as the correct type.  What we can do is override what the serialized object says and provide our own assembly information so that we can open our objects in another application.

First what we need is to create some add-ons for the SerializationBinder class that is part of System.Runtime.Serialization

sealed class SerializationHelper :
public override Type BindToType(string assemblyName, string typeName)

What the SerializationBinder class does is allow us to setup the assembly information and find the current object type that we want to deserialize as in this application, as opposed to the one it was created it.

First thing, we create an object of Type to hold the object type that we want to deserialize as

Type typeToDeserialize = null;

The biggest problem I ran into is the way that System.Reflection.Assembly returns assembly information. We can get the full name of the assembly like so

string currentAssembly = Assembly.GetExecutingAssembly().FullName;

Which gives us the fully qualified name of the current assembly, version and culture information. But we don’t need all that.

// In this case we are always using the current assembly
assemblyName = currentAssembly;

int index = typeName.IndexOf(‘.’);
string obj = typeName.Substring(index+1);

index = currentAssembly.IndexOf(‘,’);
currentAssembly = currentAssembly.Substring(0, index);

string objType = currentAssembly + "." + obj;

So here we use a little string magic to extract just the assembly name andjust the object name so that we can concatenate them together into a fully qualified object name that GetType() will understand.

// Get the type using the typeName and assemblyName
typeToDeserialize = Type.GetType(objType);

This will return the CLR loaded manifest information on the object that matches the AssemblyName.Objectname that we provided to GetType. We can then return this information.

return typeToDeserialize;

Ultimately, to make sure that your deserialization process will use this new binding formatter you need to create your binary format binder as a new instance of our SerializationHelper class.

BinaryFormatter myFormat = new BinaryFormatter();

//set up a new binder so that we can maintain assembly freedom between
//serialized objects
myFormat.Binder = new SerializationHelper();

This way, when the myFormat.Deserialize() is called, the SerializationHelper class and our new overriden method will fire, causing the assembly information to be changed to the current running assembly, allowing you to deserialize objects that your current application (or version of the same application) did not create.