Working with Remote Data in Android Application

Dheeraj Kumar Gunti

Reading Time : ( words)

Hi All, Welcome back to Knowledge Base.

Today we will see how to pull data from a remote server. The data will be in json format and the resultant data we will be consuming in our android application.

In this sample we are creating a PCL library in which we are dealing with remote data and the resultant method will be used in Android Application.

First we will start with creating a PCL Library. In this example we are using a remote url for loading data ( You can choose your own remote server.

Based on the remote json data we are creating a class with two properties - CountryCode and CountryName.

Once the class is created with the properties. We will now start creating a ViewModel which does the business logic for us.

Now we got out PCL ready with one method which returns Countries.

Now we will start creating a android project. Add new project and select Android, in that choose blank app. It creates basic template for us.

We will now edit the axml file to accomadate a list where we are going to display all the countries.

We will map the content view with Main.axml in MainActivity using SetContentView and passing the Layout resource id, it will be mapped accordingly.

Now we need to add reference to the PCL library in to our Android Project. In OnCreate method, before that we will create an object for CountriesViewModel. We are creating one more object of type List which accomodates all the countries which are coming from the method.

Now we will identify the listview which we have created in axml file using FindViewById method.

Now we will call the GetCountriesData method. As we have used Dictionary as the return type, we will remap the data to a list view by using normal foreach loop.

In Android application we are going to deal with data using adapters. In this sample we are going to use BaseAdapter of type List.

Once the adapter is created and we will map it to listview adapter. Run the application once you are done.

Happy Coding......