Xamarin.Android – debugging via WiFi

In this short post, I’m going to show you a very handy feature of Android Debug Bridge (adb) – possibility to debug Xamarin.Android apps in Visual Studio via WiFi connection.

Using ADB to debug Android apps

By default, adb is configured to “map” Android devices connected via USB ports to the computer as debug devices, which are then available e.g. in Visual Studio as the device on which our app can be deployed and debugged. In may cases we debug apps on Android emulators, which is frequently fair enough, but at some point we need to make our tests on a physical device. It may not be very comfortable to have the phone connected using USB cable all the time, especially when testing some physical sensors like accelerometer or gyroscope. For such purposes, ADB gives us the possibility to connect Android devices via WiFi instead of USB. Let’s see how to configure it.

Configure ADB to work on WiFi

The first requirement is – obviously – that both our development PC and Android device must be connected to the same WiFi network. Then we need to find out what is the IP address of our Android device – it can be checked by going to Settings -> WiFi -> Menu – Advanced settings (Android 6.0):
Android 6.0 – IP address
As soon as you have IP address of the device noted, connect it to the computer via USB port. Now we need to use adb.exe to configure it for connecting with the device via WiFi. You can either add system environmental variable pointing to where the adb.exe is stored or just open cmd, go to the catalogue where it’s located (Android\platform-tools\) and execute the following commands:
  1. Change ADB to listen on TCP port:

adb tcpip 5555 read more...

Date selection using DatePickerDialog in Xamarin.Android

In this post, we’re going to see how to provide a nice Android UI control for selecting the date using DatePickerDialog. The dialog looks as follows:
DatePickerDialog
It may be opened e.g. when clicking on a button in the app, as I used it in MoneyBack.

Creating DatePickerFragment

First of all, we will implement the dialog to be displayed within DialogFragment. Doing that our dialog will be able to be displayed as independent piece of UI on the top of any Activity. The second requirement is to implement IOnDateSetListener interface (coming from Java/Android), which provides a callback on date selection action done by the user. The DatePickerFragment meeting those two requirements may look as follows: .gist table { margin-bottom: 0; } There are few crucial parts in above-listed class: Line 1: as said before, the class derives from DialogFragment and implements IOnDateSetListener interface Line 3: here we have public static readonly string TAG variable defined – it is used as a unique identifier of the Fragment; in some cases, Fragments can be displayed without any UI – in such case the only possibility to identify and get the Fragment is by using

findFragmentByTag() read more...

SQLite-Net Extensions – one-to-one relationships

In this second short post from SQLite-Net Extensions series, we’re going to see how to create one-to-one relationships using this tiny ORM.

One-To-One

This is the simplest type of database relationship. An example could be vehicle and registration certificate – each vehicle has one and only one registration certificate, and one registration certificate is associated with one and only one vehicle (excluding some extraordinary law rules in other countries that I don’t know 🙂 ). We can model it in two ways:
  • as a one-way relationship – in this case only one of the relationship’s ends knows about the other one
  • as a both-ways (with inversion) relationship – both relationship’s ends know about each other.

One-To-One with no inversion (one-way)

This kind of relationship looks as follows:
One-To-One – one-way – class diagram
We use it when we assume it’s enough that Vehicle knows about RegistrationCertificate, but the document doesn’t necessarily need to know which car/motor it’s associated with (at least directly). In the code, we then create two model classes using SQLite-Net Extensions: .gist table { margin-bottom: 0; } .gist table { margin-bottom: 0; } What’s interesting here is the ForeignKeyAttribute defined on RegistrationCertificateId property. It is – as its name says – the foreign key to the primary key of related entity (of type RegistrationCertificate). The related entity property itself is decorated with OneToOneAttribute. There’s nothing more we need to do to have this relationship modeled. We can already use it: .gist table { margin-bottom: 0; } Nothing special here, right? It looks very similar to what we’ve seen in the previous post about many-to-many relationships. What’s interesting for us it that in the end, when Vehicle object is retrieved from the database using GetWithChildren method, its RegistrationCertificate property is filled as well:
One-To-One – filled related entity

One-To-One with inversion (both-ways)

This kind of relationship models itself as below:
One-To-One – with inversion – class diagram
What actually changed on the diagram compared to the relationship with no inversion is that now RegistrationCertificate has a property of type Vehicle (in the code – a reference to Vehicle related object and a foreign key). In our case, this is even more “real” – it would be nice if a Vehicle knows about its RegistrationCertificate, but also when we look at the certificate we’d like to see to which car it belongs. We can now model it in the code. The only thing that changes in the model classes is addition of a reference and foreign key to Vehicle in RegistrationCertificate model, so I’m presenting only this class’s updated code: .gist table { margin-bottom: 0; } What’s cool here is that we don’t need to modify our code for saving entities with relationships into SQLite database. We can simply add the following line at the end:

var certificateStored = db.GetWithChildren<RegistrationCertificate>(certificate.Id); read more...

SQLite-Net Extensions – many-to-many relationships

In today’s post we’re going to see what is SQLite-Net Extensions ORM and how to use it to create many-to-many relationship in SQLite database. The other types of relationships will be described in separate posts.

What is SQLite-Net Extensions ?

As you develop any mobile app, sooner than later you need to keep your app’s data in some persistent storage. In my MoneyBack project I’ve chosen SQLite database using SQLite.NET library for performing operations on it. This is actually very simple and easy-to-use database framework, but I recently realized I need to model some relations in my database.  SQLite.NET doesn’t offer any nice utilities to model such relations. However, if you need to model any relations in your SQLite database, there is a wrapper on SQLite.NET which allows to do that – it is SQLite-Net Extensions. It basically extends the core functionalities of SQLite.NET by adding elements that allow to easily handle relationships, including one-to-one, one-to-many, many-to-one and many-to-many. In this post we are going to see how to create many-to-many relationship using this library. I needed this kind of relationship to model the connection between Person and Event entities in my app.

Many-to-many relationship

Let’s see many-to-many relationship on an example of two entities: Person and Event. An event (entity of type Event) may contain zero or more participants (entities of type Person) whilst a person may be assigned to zero or more events. This is a typical many-to-many relationship which we are going to set up in our database now.

Install SQLite-Net Extensions

If you’ve previously been using SQLite.NET in your project – uninstall it first. I didn’t do it before starting to use SQLite-Net Extensions and I have many troubles with Visual Studio resolving my references incorrectly. SQLite-Net Extensions is a wrapper for SQLite.NET, so it already contains this library and additionally extends it by adding some extra functionalities for handling relationships. SQLite-Net Extensions can be installed as a Nuget package into your solution. According to the version you’d like to use, execute appropriate command in Package Manager Console in Visual Studio: synchronous:

Install-Package SQLiteNetExtensions -Version 1.3.0 read more...

MoneyBack – 3 weeks before the end of DSP

In today’s post I’d like to present what’s the current status of works on MoneyBack application, 3 weeks before the end of DSP competition. In general, the project hasn’t been going as well as I expected and is currently not as advanced as I’d expect it to be at this stage. There are many reasons behind that, including lack of time recently and many issues met during development, however, as I already wrote in my DSP introducing post, the most important is to survive with the project to the end of the competition and meet all requirements. The end of DSP doesn’t equal the end of MoneyBack 🙂 That’s why in this post I’d like to show you how the project looks currently and what’s still to be done. Moreover, as I promised before, I’m publishing my Trello board with tasks still to be done within the project.

UI changes

For the last days working on the project I’ve been trying to make the UI of MoneyBack some kind of “final” version, so I can easily extend it adding new functionalities and focus on development instead of spending time on interface design, which is not important for me at the moment. I met many issues with that, which I think came from using some deprecated UI elements I used (e.g. ListView and Adapters) that are not fully-supported in the newest versions of Android. Tutorials are also not really up-to-date for those components. Maybe that’s also because when I wanted to implement displaying a list of entities I looked in Google for something like “xamarin android list of elements” which lead me to this ListView and Adapters tutorial. Instead of firstly reading the whole User Interface tutorial, I wanted to implement displaying the list quickly, so I used those deprecated elements instead of implementing for instance newer and recommended RecyclerView from the beginning, which would be easier extensible now. That definitely teaches me that I should get to know a particular topic/area better and wider before deciding to use one of the possible solutions to solve a problem. Sometimes we want to implement something particular quickly, but later it produces more issues than benefits. Finally I added tabs (only one tab for People for now, but it will be easy to add new ones now) and ActionBar menu on the main Activity of the app:
MoneyBack – tabs
On the screenshot above, in the right-upper corner there is “Add” button visible when clicking on ActionBar menu. It opens a new person’s adding screen, on which I made name and email fields mandatory:
MoneyBack – adding Person
People added are then displayed on the main screen of the app in “People” tab:
MoneyBack – list of people

Code – interesting parts

Using tabs layout in an Activity
It turned out that using tabs-like layout in the Activity is pretty easy. In the AXML layout file for MainActivity I just added a FrameLayout container, within which the tabs and their contents are to be displayed: .gist table { margin-bottom: 0; } I called it tabFragmentsContainer, because within each tab we will display a Fragment. Fragment represents a part of UI and/or behavior, which is displayed within an Activity. You can think of Fragments as smaller pieces, that can be placed onto (inside) Activities. Basically, I changed PeopleListActivity to PeopleListFragment, which in fact only required changing inheritance from being a child of Activity to inheriting from ListFragment (which is a special kind of Fragment used for displaying lists of elements). The complete code of PeopleListFragment can be found in this public Gist. In the end, making MainActivity displaying tabs requires setting its ActionBar’s navigation mode to :

this.ActionBar.NavigationMode = ActionBarNavigationMode.Tabs; read more...

Android Apps Localization

Hello everyone 🙂 As you might have noticed, I’ve recently decided to take a longer break in DSP competition. Few things to do, Easter in the meantime… but of course I didn’t give up and today I’m back 😉 In this post I’d like to show you how do we localize Android apps. Let’s see!

What is localization ?

Generally, localization is a process of adapting the product or application to specific markets by adjusting its language and cultural resources accordingly. People often think that localization is only a process of translating documentation and user interface into multiple languages, but in fact it may concern many other not less important topics, e.g. formats of numeric values or dates, currencies, numbers comparison/sorting methods, symbols, national flags or even country-specific law requirements. Android supports app’s resources localization in pretty easy way. We can quite conveniently provide different versions of strings, images and layouts used in our application for different languages/regions. Let’s take a look at the basics of Android app’s localization.

Android localization basics

In every Android application, localization is based on the language user has set on his/her device. The language can be changed in Settings -> Language & input. Changing the language in this place affects both user interface’s language and region-specific settings (e.g. dates formats). To retrieve the current locale (constant/object representing selected language) in code the following statement can be used:

var currentLang = Resources.Configuration.Locale; read more...

Android Layout Types

If you’re just an Android user, you may not even know that each screen in your application has controls composed within different Layouts. Let’s see what are the main Layout Types in designing Android app.

What is a Layout ?

Layout defines a visual structure of an Activity (or app widget). It may be considered as a set of rules according to which controls (buttons, text fields, input fields etc.) are placed on the View.

Layouts structure

Basically, user interface in Android apps is built using Layouts. Each Layout is a subclass of ViewGroup class, which derives from View class, which is the basic UI building block. View is the base class for buttons, text fields etc., more precisely: for

widgets read more...

Xamarin – Android Intents

We’ve already seen what are Activities, the most basic pieces of every Android app and today’s topic is associated with it. We’re going to see how to communicate between Activities (or Application Blocks) using Intents.

Android Application Blocks

Android apps are composed of Application Blocks, which are special kind of Android classes consisting several elements bundled together, including: Everything that comes in such package is coordinated by AndroidManifest.XML file. Especially, in this XML file (or by using various attributes on Activity class) it’s possible to register our Application Block to be “callable” by the others. We’ll see more details in a while, but generally your app block is “callable” when it can be used by the other apps – probably you’ve already seen Application Chooser screen on your Android phone, e.g. when you wanted to open downloaded movie and the system asked you which video player you want to use. The same can be done with your own app – if you’re developing a dialer app, you can register it to be callable for ACTION_DIAL Activity Action. Then, as soon as any other app uses Intent to make a phone call (which we’ll see in this post), Application Chooser appears and your app will be one of the possible ones to use for making this phone call.

What is an Intent ?

Android system is designed to be loosely-coupled. Moreover, there is a principle of least privilege introduced in system’s architecture. It means that each app has access only to Blocks which it requires to work. Different Blocks don’t know much about each other (even if defined within the same application). Here’s where an Intent comes into play. Application Blocks use Intents to asynchronously communicate with each other. In general, you can think of an Intent literally – it’s the intent (or a will) to do something. By sending Intents between different components, we can coordinate complex actions such as launching email app to send a message, using Location for obtaining user’s coordinates or navigating between application’s screens. For me, we can think of Intents and their usage from two perspectives:
  1. Intent as an intent – a will to do something. In this case, you use Intent to execute some action. When creating a new Intent you need to tell it what you want to do and give it necessary parameters for such operation (e.g. for send email action, you need to provide email address parameter)
  2. Intent as a message – bidirectional information having sender, recipient and potentially some content. This can be for instance navigating to a new screen (Activity), where sender is the original Activity, recipient is the destination Activity to be opened and the content may consist some parameters to pass between two screens.
We’ll now see those two approaches in details.

Intent as an intent

In order to trigger another (external) action, e.g. camera recording or email sending, we can create an Intent and start a new Activity. Let’s see it by the example I implemented in MoneyBack – I added an additional ListActivity (PeopleListActivity class) which is the list of people added to app’s database. When a person on the list is clicked, I create an Intent in order to call his/her phone number as the following code presents: .gist table { margin-bottom: 0; } What those 4 lines of code do, is when tapping an entry from the list:
MonayBack_ListOfPeople
MoneyBack – people list Activity
it opens the phone dialer app with selected person’s phone number to call:
MoneyBack_phoneDialerCall.png
Phone Dialer opened
NOTE: If I had more than one dialer app installed (if the other dialer app has itself registered as receiver for ACTION_DIAL, of course) Android would ask me to choose which app I want to use. How did that happen? First actually interesting line of code is the following one:

var intent = new Intent(Intent.ActionDial, uri); read more...

Unit Testing Xamarin application

Today we’ll see how to add unit tests to Xamarin Android application, testing both platform-independent logic and Android-specific features.

Issue with unit tests in Visual Studio 2017

When I started to create my data access methods in MoneyBack, I really wanted to start writing even some basic unit tests of that logic. My first trial was to add a new project to my solution which contains unit tests. So I checked what kind of projects templates I have available and I I found Unit Test App (Android) project template and added it to my solution. Generated project contained TestsSample class with some unit-looking tests methods, but I had no idea how to execute them. With ReSharper installed, I didn’t have any “Run Tests” option on this project. I read somewhere on the web that this project type is used to execute tests on the device, but I couldn’t figure out how to do it. I gave up. Then I found another project template – Class Library (Android) with nUnit. Sounds better, nUnit in the name suggests unit tests, so I added this project to my solution. This time when right-clicking the project I had “Run Tests” option, but when clicking on it I got the following exception coming from ReSharper:
ReSharper_Exc
ReSharper error when executing unit tests
“Hmm… Visual Studio 2017”, I thought. “Some bugs for sure”. And I… … didn’t give up this time and with some help of folks from StackOverflow I figured out how unit tests should be done in Xamarin app. Let’s see that in the next chapters.

Levels of testing Xamarin application

There are basically three “levels” of testing Xamarin apps:
  1. Classic unit tests of pure .NET/Mono
    • standard, good old unit tests of logic independent from targeting platform (Xamarin.Android/iOS/Windows Phone)
    • unit-testing frameworks can be used (nUnit / xUnit)
  2. Platform-specific tests
    • unit tests of functionalities specific to targeting platform (e.g. Bluetooth, Location, GPS, SMS etc.)
    • specific for each platform
    • don’t contain GUI tests
    • executed on the emulator/device
  3. UI tests
    • tests of UI elements of the app and how those react for input (touch) events
    • executed by cloud/testing lab services (local or remote)
We’ll dive into the first two, UI tests is more complex topic, which requires setting up tests lab or using cloud testing services. For small projects, in the beginning it’s not necessary.

Classic platform-independent unit tests

In order to simply use ReSharper for executing unit tests of logic, which is independent from Android/iOS/Windows Phone, there is a need to add a new project using template Unit Test Project (.NET Framework) to our Xamarin solution. To such project, you can add your favourite unit-testing framework (such as nUnit or xUnit) by simply installing it from Nuget.  After, ReSharper allows to run your unit tests as in old good times:
tests_rsharper.PNG
nUnit tests executed by ReSharper
The exception I was getting with ReSharper previously was because I added the project using template Class Library (Android) which has its target set to Android device/emulator. ReSharper doesn’t know about any Android-specific (or Xamarin-specific) testing, so it was displaying unhandled error. In order to test platform-specific (in out case Android-specific) functionalities of your application, the tests need targeting runtime environment to run. It means they need to be executed on the physical device or emulator. Providers of the most popular unit-testing frameworks created wrappers for on-device testing. I’m using

NUnit Xamarin Runners read more...