Volley Network Library Integration in Kotlin

App Dev Insights
3 min readNov 4, 2017

--

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

  1. Request queuing and prioritization
    2. Effective request cache and memory management
    3. Extensibility and customization of the library to our needs
    4. Cancelling the requests

Open build.gradle and add volley support by adding
compile ‘com.android.volley:volley:1.0.0’ under dependencies section.

Open Android Manifest xml File and add internet permission

<uses-permission android:name=”android.permission.INTERNET”/>

<?xml version=”1.0" encoding=”utf-8"?>
<manifest xmlns:android=”http://schemas.android.com/apk/res/android"
package=”com.recycler.kotlinvolley”>
<uses-permission android:name=”android.permission.INTERNET”/>
<application
android:allowBackup=”true”
android:icon=”@mipmap/ic_launcher
android:label=”@string/app_name
android:name=”.network.MyApplication”
android:roundIcon=”@mipmap/ic_launcher_round
android:supportsRtl=”true”
android:theme=”@style/AppTheme”>
<activity android:name=”.MainActivity”>
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

Sample Example:

Step 1:

MainActivity.kt

import android.app.ProgressDialog
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.widget.Toast
import com.android.volley.Response
import com.android.volley.Response.Listener
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.recycler.kotlinvolley.model.MovieModel
import com.recycler.kotlinvolley.network.HttpConstants
import com.recycler.kotlinvolley.network.VolleySingletion

class MainActivity : AppCompatActivity() {

lateinit var progressDialog: ProgressDialog
lateinit var recycler_view: RecyclerView

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
recycler_view = findViewById(R.id.recycler_view) as RecyclerView
sendRequest();
}

fun setAdapter(movieList: List<MovieModel.ResultsEntity>){
var recyclerAdapter = RecyclerViewAdapter(this, movieList)
var linear = LinearLayoutManager(this)
recycler_view.layoutManager = linear
//recView.layoutManager = LinearLayoutManager(baseContext,LinearLayoutManager.VERTICAL,false)
//recView.addItemDecoration(DividerItemDecoration(this,DividerItemDecoration.VERTICAL))
//recView.itemAnimator= DefaultItemAnimator()
recycler_view.adapter = recyclerAdapter
}

fun sendRequest() {
progressDialog = ProgressDialog(this)
progressDialog.show()
val request = StringRequest(HttpConstants.BASE_URL, Listener<String> {
response ->
var movieModel = Gson().fromJson(response, MovieModel::class.java)
var movieList: List<MovieModel.ResultsEntity> = movieModel.results!!
// for (item: MovieModel.ResultsEntity in movieList) {
// println(item.original_title)
// }
setAdapter(movieList);
progressDialog.dismiss()

}, Response.ErrorListener {
error ->
loadToast(error.message)
progressDialog.dismiss()

})
//
VolleySingletion.requestQueque.add(request)
}

fun loadToast(content: String?) {
Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
}

}

Step 2

activity_main.xml

<?xml version=”1.0" encoding=”utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android=”http://schemas.android.com/apk/res/android"
xmlns:app=”http://schemas.android.com/apk/res-auto"
xmlns:tools=”http://schemas.android.com/tools"
android:layout_width=”match_parent”
android:layout_height=”match_parent”
tools:context=”com.recycler.kotlinvolley.MainActivity”>

<android.support.v7.widget.RecyclerView
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:id=”@+id/recycler_view”/>

</android.support.constraint.ConstraintLayout>

Step 3

VolleySingletion.kt

import android.content.Context
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley

/**
* Created by Manu on 10/30/2017.
*/

object VolleySingletion{

private lateinit var context: Context

val requestQueque : RequestQueue by lazy {
Volley.newRequestQueue(context)
}

val imageLoader : ImageLoader by lazy {
ImageLoader(requestQueque,LruBtimapCache() )
}

fun initConfi(context:Context){
this.context =context.applicationContext
}

}

Step 4

MyApplication.kt

import android.app.Application

/**
* Created by Manu on 10/30/2017.
*/
class MyApplication: Application() {

override fun onCreate() {
super.onCreate()
VolleySingletion.initConfi(this)
}
}

Step 5

LruBtimapCache.kt

import android.graphics.Bitmap
import android.util.LruCache
import com.android.volley.toolbox.ImageLoader

/**
* Created by Manu on 10/30/2017.
*/
class LruBtimapCache (size: Int= defaultSize ): LruCache<String, Bitmap>(size) , ImageLoader.ImageCache{

override fun getBitmap(url: String): Bitmap ?{
return get(url)
}
override fun putBitmap(url: String?, bitmap: Bitmap?) {
put(url,bitmap)
}
override fun sizeOf(key: String, value: Bitmap): Int {
return value.rowBytes*value.height/1024
}

companion object{

val defaultSize: Int get() {
val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
val cacheSize = maxMemory / 8
return cacheSize
}
}
}

Step 6

HttpConstants.kt

object HttpConstants {

var BASE_URL = “https://api.themoviedb.org/3/movie/popular?api_key=081eac77c34423c36d15affaa21680f2"
var IMAGE_URL = “http://image.tmdb.org/t/p/w300/"
}

Step 7

Response Model

MovieModel.kt

class MovieModel {

var page: Int = 0
var total_results: Int = 0
var total_pages: Int = 0
var results: List<ResultsEntity>? = null

class ResultsEntity {

var vote_count: Int = 0
var id: Int = 0
var isVideo: Boolean = false
var vote_average: Double = 0.toDouble()
var title: String? = null
var popularity: Double = 0.toDouble()
var poster_path: String? = null
var original_language: String? = null
var original_title: String? = null
var backdrop_path: String? = null
var isAdult: Boolean = false
var overview: String? = null
var release_date: String? = null
var genre_ids: List<Int>? = null
}
}

Step 8

RecyclerViewAdapter.kt

import android.content.Context
import android.support.v7.widget.CardView
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.recycler.kotlinvolley.model.MovieModel
import com.recycler.kotlinvolley.network.HttpConstants
import com.squareup.picasso.Picasso

/**
* Created by Manu on 10/30/2017.
*/

/**
* Created by Manu on 10/30/2017.
*/
class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

var act: Context? = null
var movieItem: List<MovieModel.ResultsEntity>? = null

constructor(recyclerViewActivity: Context, movieList: List<MovieModel.ResultsEntity>) {
act = recyclerViewActivity
movieItem = movieList
}

override fun getItemCount(): Int {
return movieItem?.size!!
}

override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
var view = LayoutInflater.from(act).inflate(R.layout.recycler_row, parent, false)
return ViewHolder(view)
}

override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
holder?.text_list?.setText(movieItem!![position].original_title)
holder?.image_list?.loadUrl(HttpConstants.IMAGE_URL + movieItem!![position].poster_path as String)
}

class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
var text_list: TextView? = itemView?.findViewById(R.id.text_wadah) as TextView?
var image_list: ImageView? = itemView?.findViewById(R.id.image_wadah) as ImageView?
var card_list: CardView? = itemView?.findViewById(R.id.card_view_wadah) as CardView?
}

fun ImageView.loadUrl(url: String) {
Picasso.with(context).load(url).into(this)
}

}

Step 9

recycler_row.xml

<?xml version=”1.0" encoding=”utf-8"?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android"
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
xmlns:app=”http://schemas.android.com/apk/res-auto"
android:orientation=”vertical”
android:background=”@android:color/white”>

<android.support.v7.widget.CardView
android:id=”@+id/card_view_wadah”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_marginStart=”16dp”
android:layout_marginEnd=”16dp”
android:layout_marginTop=”5dp”
android:layout_marginBottom=”5dp”
app:cardCornerRadius=”5dp”>

<LinearLayout
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:background=”@android:color/white”>

<ImageView
android:id=”@+id/image_wadah”
android:layout_width=”70dp”
android:layout_height=”100dp”
android:layout_margin=”10dp”
android:src=”@drawable/ic_launcher” />

<TextView
android:id=”@+id/text_wadah”
android:layout_width=”match_parent”
android:layout_height=”wrap_content”
android:layout_gravity=”center”
android:layout_margin=”10dp”
android:gravity=”center|start”
android:text=”Dart”
android:textColor=”#000000"
android:textSize=”16sp” />
</LinearLayout>

</android.support.v7.widget.CardView>

Sample source code: https://github.com/Manuaravind1989/Kotlin-Volley

--

--