Developing a Weather Application with Kotlin on Android Studio Part-2

https://kotlinlang.org/assets/images/twitter-card/kotlin_800x320.png

As Kotlin is announced as an official language for Android development, i have started to learn how to use Kotlin in Android Development by developing a weather application with the libraries Retrofit, Dagger and Glide. While doing that, i wanted to share my experience and how i proceeded with development of this application.

In the first part of the post (you can find it here), i have talked about how we setup our environment for using the libraries. In this one, we will continue with creating the functional part and data parsing. If you are ready, let’s start!

Before creating any data class for any project, you have to observe your data from the server and decide on, what you are going to need.

For OpenWeatherAPI we can check sample data and their data architecture under JSON title to decide on what to expect or what to use in our application.

After i check the information above, i have decided to create data classes as follows.

First, let’s create a folder, under main package folder, called data.
In Kotlin, we have something called data classes. They provide data and eliminate getters and setters.

Let’s create a data class called WeatherResponse. This class will be our data class for retrieving main response.

We notice three new things here. City and ForecastDetail are other data classes that we are going to create for retrieving more detailed data. SerializedName is an annotation provided by Gson that indicates this member should be serialized to JSON with the provided name value as its field name.

Let’s proceed with creating City data class.

And now let’s create ForecastDetail.

We need to add two more data classes for Temperature and WeatherDescription. We will create those as same as we have created the previous data classes.

First Temperature

Afterwards WeatherDescription is created.

Now we are all set with the data classes.

Creating MainView

In this application, I would like to implement a simple MVP structure, so we can separate functionality and view related things from each other.

Let’s start by creating a folder called ui under our main package folder. Afterwards continue by creating a file called MainView. This will be an interface containing our view operations.

Now we have new items. ForecastItemViewModel and ErrorTypes. ForecastItemViewModel is a data class that we can combine the data we need to show in our RecyclerView. ErrorTypes is a enum class for creating error categories for showing different error messages.

If you are familiar with enum classes, it should not be a huge difference to you. But in ForecastItemViewModel data class, we see that we are assigning some values in our constructor and this is a new thing if you are developing with Java. This is called Default Arguments. It is really useful if you are not sure that, the value that you are retrieving is not null or will be assigned. You can assign a default value to handle this case.

We are all set with the MainView. Let’s continue with MainPresenter.

In our MainPresenter we will be doing our network call and create our list for showing the data on server.

First let’s create a folder under our main package with name presenter. Afterwards create a file named MainPresenter. Afterwards initial state of class will look like this.

When we are defining the class, by declaring a value in the title we are creating our constructor. So our class is ready with the constructor.

With the snippet above, we have injected our OpenWeatherAPI instance. You may recognize a new word lateinit. It is used for cases that we are initializing the variable not in the constructor but later on. You may read the more detailed explanation with the link above.

Let’s continue with the api call method:

Biggest thing here is the let keyword. This keyword is really useful for situations that we care about null safety. Inside let parentheses, it will be only executed if the value before that keyword is not null.

Otherwise we can handle what we are going to do by using the Elvis operator “?:” after the end of parentheses. In our case, we have decided to show an error toast.

There is only one step left for finishing up MainPresenter. Creating createListForView method.

Okay with the new method above two points are coming up front. First is mutableListOf. Other one is in for loop we are creating our ForecastItemViewModel instance with attributes. While assigning these attributes we are using the argument names without being binded of the order. This is called named arguments.

Now we are all set with the MainPresenter. Next step is modifying MainActivity.

As we know, we have an activity in this state right now.

We will start with implementing our MainView interface into that Activity. For implementing the interface we are adding the interface name after a comma after activity extension, after doing that we are going to be needed to implement our methods. We will do that by the help of Android Studio and we will have this at the end.

Now we will add our search view to our toolbar.For that purpose we need to create a menu. If it is not created create a folder called menu under res (menu/res). After that create a menu xml file and add these lines there:

For using this we need to override our onCrateOptionsMenu method to inflate the search view and use it.

We need to add this code snippet for that purpose. One of the first things you will recognise is that, Kotlin gets rid of all getters and uses variable names instead.

With the if statement above, we are actually working with smart casts. As you notice we have not cast the menu item to anything. When we check it in the if statement, it automatically casted. Therefore we are able to use SearchView specific things in if statement.

Before we move on with filling out our overriden functions, i would like to add 3 methods.

With these 3 methods we are seeing three important things about Kotlin.

  • First one is called single expression function. As we understand from the name if we only have one expression we do not have to care about curly braces. We can implement function as we see above.
  • Second one is called inline function. We use this method to do our casting for ForecastAdapter.
  • Third one is my personal favourite, it is called extension functions. With this function we are able to create a toast message in activity by only calling. toast(message) snippet.

Now let’s continue with filling out the implemented methods and creating some necessary methods. Before that i would love to talk about an important thing that Kotlin also served us. It is called, Kotlin Android Extensions. If you have created your application with the Canary version, it is already implemented. For the stable version of Android, you need to implement it as in the link above.

This is a useful tool that we can use it to reach views with their ids which we defined in XML. So this eliminates a huge number of boiler plate code.

Let’s continue with modifying activity_main.xml.

We have a RecyclerView for showing our list. ProgressBar to show while loading stuff and textview to show when we do not have any results.

Now we are adding a method called injectDI() to our onCreate method. We will create this method now and do our injection with our presenter.

We have created a presenter value and use it for injection above.

Above, we have created a method. In this method we are seeing a special keyword called apply. This keyword gives us opportunity to add values and add all of them at once to the specific object.

After adding these methods, we can modify our onCreate method as follows.

Let’s fill out the methods. Let’s start with showSpinner and hideSpinner methods.

And continue with adding showErrorToast method.

In this method, we are seeing the switch statement that we know in java as when statement. In each case direction is stated by a lambda.

Lastly we will add updateForecast method.

As we see, for making this adapter type safe for calling the addForecast method, we have used our inline function.

Last step is to add our Adapter!

First we need to create our view to show in the list as an item. Let’s create a xml file under layout folder called forecast_list_item.xml.

After that we start with adding an adapter folder under ui. And create a ForecastAdapter class for adapter. And add the code below.

In this class we can see something new in ForecastViewHolder class’ bind method.

"${forecastElement.degreeDay} °C ${forecastElement.description}"

In the text snippet above, we are seeing that we can directly implement a value from the object to our text by $ sign and variable name. It is called string templates.

Now if you delete the comments from the commented out sections that we had before and add the string and dimension data as shown below, you will see that your application is working just fine.

And we are done! Congratulations if you make it these far.

At the end, our app will behave like this.

In conclusion, of course this was too much information to take and it is sure that for making everything concrete, i would suggest you to create your own project and implement all the things by yourself by understanding each word.

You may find the repository for the project here.

Congratulations to all of you, now you have simple project in Kotlin. If anything is unclear or if you have any questions, do not hesitate to drop a message or comment.

Happy Coding.

Salih.