Kotlin series has been developed keeping in mind, you are already familiar at least at beginner’s level.
This is the Seventh milestone towards our Kotlin series. Go to the sixth milestone if you haven’t done so.
In this series, we will simply follow the coding challenges developed for the Android Developer Fundamentals Course, Unit 3— Lesson7.
The topics we will learn are:
- AsyncTask
- AsyncTaskLoader
- Retrofit 2.0
- Gson
The POJO in Kotlin
- It’s more concise than in Java. And, we can denote if the fields can be null which will make it more safer from the dreadful NullPointerException.
class Books {
@SerializedName("items")
var items: List<Item>? = null // Denotes field can be null @SerializedName("kind")
var kind: String // Denotes field cannot be null @SerializedName("totalItems")
var totalItems: Long? = null
}
How to use AsyncTask in kotlin?
- Basically asyncTask code is pretty much the same as in java. Noteable, is the way we are making the constructor of AsyncTask class.
// We can denote Class as internal class; note the way we are passing the constructor parameters
internal class SimpleAsyncTask(private val textView: TextView) :
AsyncTask<Void, Void, String>() { // Execute long task here
override fun doInBackground(vararg voids: Void): String {
........
}// do things with output
override fun onPostExecute(result: String) {
.....
}
}// Calling the AsyncTask
SimpleAsyncTask("someString").execute()
How to use AsyncTaskLoader in kotlin?
- Creating the Loader is the same as in Java.
// Constructor for the asyncLoader class
class MyLoader(context: Context, private val mQueryString: String) : AsyncTaskLoader<String>(context) {
// start loading
override fun onStartLoading() {
forceLoad() // Starts the loadInBackground method
}
// background work
override fun loadInBackground(): String? {
.........
}
}
- We can also initialize stuffs in the constructor with init constructor.
// We can have constructor using init constructor
init {
items = ArrayList()
items.add(queryString)
loadAsyncTask()
}
- The asyncTaskLoader is also the same we implement LoaderManager.LoaderCallbacks<> and override the loader callbacks.
// Implementing LoaderCallbacks in MainActivity class
class MainActivity : AppCompatActivity(), LoaderManager.LoaderCallbacks<String> {// Creating the loader
override fun onCreateLoader(id: Int, args: Bundle): Loader<String> {
return MyLoader(this, args.getString("queryString")!!)
} // Loader onLoadFinished method
override fun onLoadFinished(loader: Loader<String>, data: String) {
}// Loader onLoaderReset method
override fun onLoaderReset(loader: Loader<String>) {
}
}
How to do network class in kotlin with Retrofit 2.0?
- Creating the RetrofitServiceApi interface. The return type is Call<Books> this Call class will allow us to execute the request and know if the request was successful or not, also to extract the response data with given generic type.
interface GoogleBooksApiService {
@GET("v1/volumes?")
fun getBookByName(@Query("q") bookName: String,
@Query("maxResults") maxResult: String,
@Query("printType") printType: String)
: Call<Books>
}
- Building the Retrofit Rest Client with a Companion Object. We can use it to declare an object inside a class. It’s like static member in other languages, but in run-time they are still instance members of real objects.
companion object {
fun apiService(): GoogleBooksApiService {
val retrofit = Retrofit.Builder()
.baseUrl("https://www.googleapis.com/books/")
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofit.create(GoogleBooksApiService::class.java)
}
}
- We can convert the above Retrofit Rest Client code using Single Expression Function inside the function body.
fun apiService() = Retrofit.Builder()
.baseUrl("https://www.googleapis.com/books/")
.addConverterFactory(GsonConverterFactory.create())
.build().create(GoogleBooksApiService::class.java)
- Getting the response by simply calling the execute in the Retrofit call object.
val response = call.execute()
return if (response.isSuccessful) {
val result = response.body()
result
}
Project Source code: RecyclerView in Kotlin
The Eight milestone in this series.
8. RxJava & RxAndroid in Kotlin
References:
- Using Kotlin for Android development ~ Kotlin.org
- Resources to Learn Kotlin ~ developer.android
- Video of Lectures ~ youtube.com
- Retrofit API Endpoints ~ futurestud.io
- API — Retrofit & Kotlin ~ blog
- Kotlin initializers ~ blog
- Single-Expression functions ~ Kotlin.org