A Complete Tutorial to Connect Android with ASP.NET Core Web API

Last Updated on February 7, 2021 by Aram

In this tutorial we will learn how to Connect Android with ASP.NET Core Web API. We will build an Android app to show a list of technical blogs with categories.

Using Retrofit 2, the Android app will be connected to the RESTful APIs that we will build using the latest technology by Microsoft and the open source community: ASP.NET Core Web API 5.

Our data will reside in a local SQLServer Express Database and will be accessed from our Web API project using Entity Framework Core 5.

This is a full-stack development tutorial, we will tap into different layers of development (frontend, backend, database) with different languages (Java, C#, SQL) and technologies (Android, ASP.NET Core Web API, SQL Server Express).

So let’s start learning how to Connect Android with ASP.NET Core Web API.

Preparing the Database

We will create our database inside an SQL Server Express installed on a local machine, so if you don’t have it already installed please go ahead download and install the latest updates of SQL Server Management Studio and SQL Server Express

Once you are able to connect to the SQL Server Express using the SQL Server Management studio, you can go ahead and create a new Database and name it ‘BlogsDb’.

Once the Database is created, run the below script to create the needed tables and insert sample data into them, so we can kick-start our tutorial.

Once the query is run, refresh the BlogsDb from the Object explorer then you should be able to see the new tables created within the BlogsDb Database

The ASP.NET Core Web API Project

Now we will move to our Web API part to build the RESTful APIs and connect to our database using the ASP.NET Core Web API Technology

Creating a new ASP.NET Core Web API Project

Start Visual studio 2019, make sure you are using the latest update 16.8.x which includes the latest version of .NET 5

Choose ASP.NET Core Web Application and then give it a name like ‘BlogsApi’ then choose create

Then choose API and press create

Wait until Visual Studio prepares the template API project for you, then press F5 or Run. You should see swagger page on your default browser indicating that your Web API project is up and running fine on your local machine which is your IIS Express (localhost)

Now let’s start by preparing our entities and dbcontext class that will be used to connect to your database using the Entity Framework Core library.

Entities

Let’s create a new folder with name ‘Entities’ and add a class inside it with name ‘Blog’

Next, let’s add another class with name ‘Category’

Importing EF Core

Before adding the DbContext, we will need to install the nuget packages for EF Core and EF Core SqlServer :

Entity Framework Core and Entity

Creating the DbContext

Now, we want to add our DbContext inherited class, this will inherit the Entity Framework Core DbContext class and will be used to connect the entities and any other configurations with our database

Below is the class for the BlogsDbContext that will inherit from the DbContext of EF Core:

Now let’s plug in the database within the services collection. You will need to add the below code inside the startup class in the ConfigureServices method:

Adding Connection String to appsettings.json

Open appsettings.json file and let’s add a section for our new connection string, it should look as the below:

Creating Services and Interfaces

In order to have a some separation in the functionalities and to improve the traceability and testability of our web API project, we will introduce services that will act as the business layer and will hold the business logic while being able to access the DbContext object. the DbContext object will be injected into the services constructors to be used.

The services will implement interfaces so that we can rely on abstractions rather than concrete implementations. This is very important principal to follow so that you can improve your code’s testability and traceability.

Interfaces

Create a new folder with name ‘Interfaces’, then add a new item, you will need to choose interface and name it ‘IBlogService’

then add another interface and name it ‘ICategoryService’

Services

Create a new folder with name ‘Services’, then add a class with name ‘BlogService’

And add another class with name ‘CategoryService’

Now to make sure that we have the correct binding between the service and interface when injecting the service into the constructor through the interface, we need to configure this within the startup ConfigureServices method

Creating Models (DTO)

It is very important to know that it is not recommended that you return the entity objects as-is to your clients, because since the entities represent the exact structure of your database, you don’t want your clients or (the front end world) to know about this structure, it might not cause a serious threat or problem however it might cause some leakage in your internal system design and might fall into your competitor’s hands.

The other reason to not return the entity object is to prevent the tightly coupling with your backend structure, if you are about to modify any of the tables then chances are that your clients might be affected and might cause problems at their side.

So to avoid such issues and stay flexible and loosely coupled, you should introduce DTO (Data Transfer Objects) or Models, which will be new classes that will bind to your entity classes, which may include all or part of your entity properties with the same or different names or data types.

So let’s go ahead and create a new folder with name ‘Models’

and then add a new class to it with name BlogModel

Now we need another class for CategoryModel

Perfect! So what will happen now, we will convert the entity classes to model classes, and return them for our clients.

Usually, it is a good idea to have a helper class to hold the conversion logic and you only call it from your controller.

So, before writing our controllers, let’s create our helpers. Create a new folder with name ‘Helpers’ and then inside it create a new class with name BlogHelper

And then create another class with name CategoryHelper, it will include the method to convert the categories entities to models:

Now we are ready to add our controllers and glue all the components together.

Controllers

Let’s create our endpoints that will be used as the entry points or the gateway to our database to access the tables.

In the controllers folder, add a new controller with name ‘BlogsController’. This controller will have one endpoint to return all the blogs, as you can see in Get() method, we call the GetAllBlogs method and then the result is passed to our converter method to convert the entities type to models type, and then the result is returned in the response body of the http 200 ok

As you can also notice, we are using the constructor injection of the BlogsController to provide the instance of BlogService through the abstract interface IBlogService.

Next, let’s add another controller with name ‘CategoriesController’, this will include 2 endpoints: one to get all categories and the other one to get the blogs within a given category (id)

Now, to make sure everything is working fine we need to run the Web API project and see what results we will get.

One important note here is that we won’t be running our APIs on IIS Express, we will run it on the default hosting of ASP.NET Core Web API, why? Because we will run our Android App on an emulator and the emulator must connect to IP Address 10.0.2.2 which is another alias for 127.0.0.1 but not localhost, therefore, the emulator won’t be able to connect to IIS Express but it will connect to the default host of ASP.NET Core Web API.

I will show you how this will work later in this tutorial.

Accordingly, from your Visual Studio , click on the run dropdown button and select BlogsApi instead of IIS Express

Then press on the BlogsApi button itself. This will trigger a terminal window with the hosting provider of ASP.NET Core Web API bootstrapping your Web API Project

And then you should be presented with your default browser showing a Swagger documentation of the BlogsApi.

Your API project is now hosted on localhost under 2 ports : 5001 https and 5000 http.

For this tutorial, we will connect to http://localhost:5000 because Android requires a self-signed certificate to connect to https, so this would be outside the scope of this tutorial.

Remember that on production you should always connect your web or mobile app to https and build your RESTful APIs to work on https based domains.

Of course we can test our APIs on Swagger through the easy provided UI to navigate and test the endpoints, however I prefer to use Postman.

Testing the APIs on Postman

If you don’t have Postman installed, then go ahead download it from here

Then open Postman and create a new collection with name ‘BlogsApi’

Create a new request with Get Categories. This will point to the endpoint that returns all the categories

Now let’s create another request to retrieve all the blogs under a provided CategoryId

Now the last request that we want to test is retreiving all the blogs chronologically ordered from the newest blog.

There you go we have finished building and testing our RESTful APIs using ASP.NET Core Web API

Of course these are just small samples of what you can do with this powerful technology, you can still add POST, PUT, DELETE or even other GET requests to the project to make it larger and more comprehensive.

Now let’s jump to the front-end part of our tutorial and prepare our Android App to connect to our RESTful APIs that we have just built using ASP.NET Core Web API Technology.

Building the Android App

Our Android App will display all the Categories of the blogs through nicely formatted cards within a launch screen that will have bottom navigation with 3 buttons: Categories, Latest Blogs and Notifications.

Whenever the user taps a card, it will open a new screen displaying a scrollable list of blogs under that specific category, and then if the user taps any given blog, the app will show all the blog details in a new screen with a clickable link to open the blog on mobile browser. At any time, the user can go back to previous screens with the default device back button.

As mentioned earlier in this tutorial, we will connect Android with ASP.NET Core Web API using Retrofit 2

So let’s begin with creating our Android app, I will be using Android Studio 4.1.2 , if you don’t have Android Studio, you can go ahead, download and install it from the Official Android Developer Page , if you have an older version, I would suggest you update your version.

Now open Android Studio, and click Create New Project

Then Choose Bottom Navigation Activity from the Project template screen:

After that, in the project configuration screen, change the name to blogs. You can also change the package name to whatever you prefer, usually the naming is based on the product you have so if you have a website, then it can be like com.codingsonata.blogs . Let’s keep it like com.demo.blogs for now

For the Minimum SDK, we will choose API 21: Android 5.0 (Lollipop) , of course this is usually decided based on the business requirements for what devices will be supported and which APIs of the Android SDK will be used.

Press Finish to let Android Studio start preparing your project:

Let’s run this sample app to check that the emulator will be booting and running fine and the template app will normally load.

So, once you see the below screen on the emulator it means that you are all set up to start building the blogs app that will connect to our RESTful APIs built with ASP.NET Core Web API

Now close the emulator, and head back to Android Studio.

Setting up Retrofit 2

As mentioned previously in this article, we will be using Retrofit 2 to connect to our ASP.NET Core Web API , if you are new to Retrofit 2, I would suggest first that you check my tutorial series ‘Retrofit Tutorial in Android ‘ , it will give you a full walkthrough about Retrofit and how to use it in Android to connect to live APIs

So open your build.gradle (:app) file and navigate to the dependencies section, add the below references to get Retrofit 2

Once added, sync your project to let gradle download and build the project with the new libraries

Let’ prepare our app to connect to our RESTful APIs

Create a new package with name ‘data’ and place it directly under com.example.blogs package

The Models

Add a new package under data with name ‘model’, this will include the POJO classes that will hold and bind the data from the RESTful endpoints

Create Blog class

Then create another class with name ‘Category’

Now add a new package under data with name ‘remote’ , this will include the classes that will initiate and connect to Retrofit.

Retrofit 2 Service and Interface

We will need to create an interface that will use annotations from Retrofit library to match and identify the endpoints. The interface name is IBlogsApi, you can give whatever name you prefer, just make sure it starts with I to stay with conventions:

Then, let’s add RetrofitService class, we will define a static method to create the retrofit instance

If you notice above in the baseUrl string, we are connecting to 10.0.2.2 , as mentioned previously this is an alias to the host loopback interface which redirects to 127.0.0.1 or localhost, but we didn’t specify localhost in the baseUrl, because the Android emulator can only connect to this IP address 10.0.2.2 with the port specifying 5000 which is where the ASP.NET Core Web API is hosted.

Now before moving to the next part of calling the create method of RetrofitService, we will extend the Application class in a new MainApplication class and inside it we will keep a static reference to the BlogsApiManager and we will override the onCreate Method of the application to get a singleton instance of the BlogsApiManager

So let’s add a new class directly under the root package corp.example.blogs

BlogsApi Manager

Next, we will define a manager class that will hold a singleton instance to RetrofitService and will include the methods that will bind to the RESTful APIs through Retrofit Callback events:

The Repository

In this tutorial, our data source is only coming via the remote service of RESTful APIs that we built using ASP.NET Core Web API, we don’t have local data source to connect to, so the repository layer will only include calls to the BlogsApiManager and will hold the data within LiveData objects, which later will be propagated to the UI layer view the ModelView of the specific UI component.

This structure of layering the services falls under MVVM architectural design pattern, using the LiveData and ModelView components of Android X

So let’s add a new package under data with name ‘repository’, this will include the repository of our blogs app

Now let’s prepare the UI part of the app.

UI

Expand the ui package in your project explorer, you will notice 3 packages created for you by the template we have chosen earlier.

also you will notice MainActivity created for you, this is the hosting activity for the navigation host fragment, which will use the BottomNavigationView to switch between the different fragments

This is the code for MainActivity, you don’t have to do anything specific on it

We will need to rename the home package to categories, so right click on home package and refactor -> rename (or just use the Shift + F6 in your keyboard), and use the name ‘categories’

Categories package

Before we jump in the fragment part of the categories section, we will create a ViewModel for it which will act as the intermediary layer between the UI and the model.

So add a new class with CategoriesViewModel

And now let’s add a factory class, CategoriesViewModelFactory, that will instantiate the ViewModel Instance within the fragment

We want to display the categories through a recyclerview with a GridLayoutManager having 2 categories per row, and each category will be displayed within a card view.

So let’s start by preparing the category item layout that will be used to display the category card

Category Item Layout

navigate to res/layout folder and add a new layout resource file with name category_item.xml

Categories Adapter

Now let’s create the adapter that will bind the data to the recyclerview using the card_item layout

Inside the categories package, create a new class with name ‘CategoriesAdapter’

OnItemClickListener

In the above code, you will notice

we added a click listener for our categories card items so that whenever the user taps a category, we can know which category was selected and thus transition to a new screen with the blogs that are listed under the selected category.

So open ui package and create a new package with name ‘common’ and inside it add an interface with name ‘OnItemClickListener’

Categories Fragment

Now navigate to HomeFragment and rename it to CategoriesFragment. This will hold all the UI related code to update the view, it will observe the CategoriesViewModel for any changes and then update the recyclerview and its adapter accordingly, we will also display a progress while the API call is happening and hide it once results are received.

Let’s create the fragment_categories.xml layout now:

BlogsActivity

Now we are done from the Categories Fragment part, its time to create a new activity that will display all the blogs under the selected category.

The BlogsActivity will be called from the CategoriesFragment and will receive an intent with the category object parsed as json and the CallerActivity so that the BlogsActivity will display all its blogs inside a fragment that will be shared and used in the 2nd layout of the bottom navigation ‘latest blogs’

So under ui package, create a new package with name ‘blogs’, inside it create a new Activity, choose blank Activity

Let’s add an xml layout for activity_blogs, it will contain a FragmentContainerView to host the fragment and an AppBarLayout to show the top bar with the category name, as you can see from the previous code, we are setting the activity’s title to the selected category name, after reading the intent and converting it to Category object from Json string format.

So below is the activity_blogs.xml

BlogsFragment

Now let’s create the BlogsFragment. As mentioned previously, this fragment will be used from 2 different places so it will fork its arguments to check the CallerActivity, if it is coming from MainActivity, then it means that this fragment will show the blogs of the selected category, because we are passing the CallerActivity right from the CategoriesFragment which is hosted under the MainActivity latest blogs, so it will call the getBlogs method otherwise it will show the latest blogs

And let’s explore the fragment_blogs xml layout after you create in in the res/layout folder:

the blogs fragment includes a recyclerview to display the list of blogs an has ContentLoadingProgressBar to display a nice spinner loading for the user while the app is doing the request.
BlogsViewModel

The BlogsViewModel will include 2 methods from the BlogsRepository one to get the blogs under a selected category and the other to get the latest categories ordered by date

BlogsViewModelFactory

And here is the the BlogsViewModelFactory, it is similar to the CategoriesViewModelFactory in terms of using the BlogsRepository to obtain the singleton instance the BlogsApiManager

BlogsAdapter

And now we will create the BlogsAdapter, it will be used to bind the blog_item to the blogs data source passed from the fragment

And let’s see how the blog_item.xml layout would look like the below:

So far we have implemented both the Cateogies and the Blogs screens, now let’s implement the screen that will receive the blog details and display it for the user

BlogsInfoActivity

under ui package, add a new package with name blog.info and inside it create a new Blank Activity and name it BlogInfoActivity, inside this activity we will display all the blog information, there is not need to create a fragment for this, because in this tutorial we will not have a different screen or section to display the blog information.

The BlogsInfoActivity should have this code:

If you notice from the last line in the above source code, we added a method to format the date

the getFormattedDate takes the string that includes the date of the blog in UTC, and formats it to display it in a more presentable date time format

let’s head to data package and create a new package with name helper and inside it add a new class with name ‘DateHelper’

so let’s go back to the res/layout folder and create a new layout resource with name ‘activity_blog_info.xml’

This is the source for activity_blog_info.xml , you can feel free to design it in the way you prefer:

Adding Network Configuration

Before testing our work on the emulator we just need to do one last step, we will add a new package with name xml under the res folder and inside it we will add an xml file with name network_security_config

I have added a important note inside this you keep it in mind always, that you should not use cleartextTrafficPermitted=”true” on production environment, which means you should always connect to https APIs when working on business products. This is added only because we are testing our app on an emulator that is connected to localhost via the special IP Address (10.0.2.2), so we are connecting to our APIs via http calls.

Let’s include the above network_security_config inside our application manifest, add the below line to the <application tag

And since we are still in the manifest, make sure you specify the MainActivity to be the main and launcher activity.

Eventually, your manifest should look like this:

And your android folder structure should appear as this

Android Blogs app folder structure

Testing the Android app on emulator

Now let’s run our application to see how would it appear on the emulator.

The first screen (launch screen), is the MainActivity and the first displayed fragment is the categories fragment, so we will see the categories populated in cards through the grid layout

Now if we tap on Front End Development, we will see a new screen with the blogs populated vertically on the screen and the title will be Front End Development

Then if we tap on Coding Sonata, we will see another screen with all the blog details related to the selected blog

Now, let’s go back twice to the main screen that shows the categories and select desktop development, we didn’t add any blog under this category, so on the next screen we will see a Snackbar telling us that there are no blogs under this category

Now let’s go back to the main screen and tap the latest blogs button, you should see the latest blogs sorted by date

and this is how the loading progress spinner will show whenever there is a call happening to the API to get the categories

Summary

So that’s it, we have managed to build and connect Android to ASP.NET Core Web API in .NET 5, we used Entity Framework Core 5 to connect to SQL Server Express Database. The Android app targeting Android SDK 30 with min sdk 21 connects to the RESTful APIs using Retrofit 2.

I hope you had learned how to Connect Android with ASP.NET Core Web API.

You can find the full source code for both the API and App project on GitHub.

Feel free to leave your feedback in the comments section and if you like this tutorial please use the social button on the left to share it with your community.

Subscribe with your email to be the first to receive the updates and new articles that I add to this blog.

Check my other articles about Android and ASP.NET Core Web API

Bonus

while you read and explore this long tutorial, I chosen for you to enjoy the enchanting tones of this modern classical list of contemporary masterpieces by the virtuoso composer and pianist: Yiruma

The Best Of YIRUMA Yiruma’s Greatest Hits ~ Best Piano (HD/HQ)