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.
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:
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.
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.
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.
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.
In this lesson, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user.
We’re also going to explore the Model-View-Controller pattern, which is present in the design of apps made on the Xamarin platform.
If you’re not already familiar with the MVC pattern of application development, let’s start with an overview.
Model–view–controller (MVC) is a software architectural pattern for implementing user interfaces on computers. It divides a given software application into three interconnected parts, so as to separate internal representations of information from the ways that information is presented to or accepted from the user.
MVC is a standard design pattern that many developers are familiar with. Some types of Web applications will benefit from the MVC framework. Others will continue to use the traditional ASP.NET application pattern that is based on Web Forms and postbacks. Other types of Web applications will combine the two approaches; neither approach excludes the other.
The MVC framework includes the following components:
Models. Model objects are the parts of the application that implement the logic for the application’s data domain. Often, model objects retrieve and store model state in a database. For example, a Product object might retrieve information from a database, operate on it, and then write updated information back to a Products table in a SQL Server database.In small applications, the model is often a conceptual separation instead of a physical one. For example, if the application only reads a dataset and sends it to the view, the application does not have a physical model layer and associated classes. In that case, the dataset takes on the role of a model object.
Views. Views are the components that display the application’s user interface (UI). Typically, this UI is created from the model data. An example would be an edit view of a Products table that displays text boxes, drop-down lists, and check boxes based on the current state of a Productobject.
Controllers. Controllers are the components that handle user interaction, work with the model, and ultimately select a view to render that displays UI. In an MVC application, the view only displays information; the controller handles and responds to user input and interaction. For example, the controller handles query-string values, and passes these values to the model, which in turn might use these values to query the database.
The MVC pattern helps you create applications that separate the different aspects of the application (input logic, business logic, and UI logic), while providing a loose coupling between these elements. The pattern specifies where each kind of logic should be located in the application. The UI logic belongs in the view. Input logic belongs in the controller. Business logic belongs in the model. This separation helps you manage complexity when you build an application, because it enables you to focus on one aspect of the implementation at a time. For example, you can focus on the view without depending on the business logic.
The loose coupling between the three main components of an MVC application also promotes parallel development. For example, one developer can work on the view, a second developer can work on the controller logic, and a third developer can focus on the business logic in the model.
Using Navigation in iOS
A Storyboard is a visual representation of the appearance and flow of your application. Xamarin has introduced a Designer to allow Xamarin.iOS applications to take advantage of storyboards, so you can design your application screen visually and access the views, controllers and segues with C# for more control.
In this section, you’ll learn how to gather input from the user and make decisions with that information. You’ll also learn how to display information to the user. We’ll also look at how to navigate between multiple views in your Android application.
Adding an Activity
In order to add code to the app that will respond when the user clicks the button, we have to add an Activity. Your app can be made up of many activities that happen together or at various times.
An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI
While activities are often presented to the user as full-screen windows, they can also be used in other ways: as floating windows (via a theme with windowIsFloating set) or embedded inside of another activity (using ActivityGroup).
There are two methods almost all subclasses of Activity will implement:
onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.
onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).
What do you Intend to do?
From the Android documentation:
An Intent provides a facility for performing late runtime binding between the code in different applications. Its most significant use is in the launching of activities, where it can be thought of as the glue between activities. It is basically a passive data structure holding an abstract description of an action to be performed.
That’s some engineering speak, right?
So what is an Intent? An Intent is a description of an operation to be performed. An intent allows you to start an activity in another app by describing a simple action you’d like to perform (such as “view a map” or “take a picture”) in an Intent object.
This type of intent is called an implicit intent because it does not specify the app component to start, but instead specifies an action and provides some data with which to perform the action.
An Intent in Xamarin is pretty easy. You create the Intent object, provide any additional information you want to pass to the Intent and call StartActivity to get it kicked off.
var intent = new Intent(this, typeof(YourActivityHere));
When considering how to build iOS and Android applications, many people think that the native languages, Objective-C, Swift, and Java, are the only choice. However, over the past few years, an entire new ecosystem of platforms for building mobile applications has emerged.
Xamarin is unique in this space by offering a single language – C#, class library, and runtime that works across all three mobile platforms of iOS, Android, and Windows Phone (Windows Phone’s native language is already C#), while still compiling native (non-interpreted) applications that are performing well enough even for demanding games.
Testing Your Apps
If you do not have a device that you can use for testing, you will need to use an emulator and run your applications in the test environment.
Xamarin Android Player
The Xamarin Android Player relies on virtualization and OpenGL. This means that it cannot run inside virtual machine instances nor can it work over Remote Desktop or VNC. Further system requirements can be found in the guide linked below.
Xamarin mobile applications can be deployed to physical devices via USB for testing and debugging (Xamarin.Mac apps can be tested directly on the development computer; Apple Watch apps are deployed first to the paired iPhone). You will need to be sure that your device is setup for development if you wish to test on it. Here is the guide that can help you get started: https://developer.xamarin.com/guides/ios/getting_started/installation/device_provisioning/
Since you are learning the basics of C# here, why not take it a step further and learn how to write mobile apps using the Windows Phone mobile platform? All of your C# knowledge you’ve learned here can start earning you money quickly on the app store!
Existing C# Learning students get $10 off of this course. Email me for your coupon code!
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.
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?
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.
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.
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:
Basic concepts of programming
Development software / IDEs
Foundational knowledge in computing
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.
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;
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
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.
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
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.