Skip to content

Volley Android Example JSON Parsing – Kotlin

Volley Android is used for network calls from the Android application. With a volley library in android application development, you can make easy network calls. You can make Volley HTTP Requests GET, POST, PUT, DELETE. It saves a lot of time and also provides network caching.

Volley Library: is an HTTP library that makes networking for Android apps easier and most importantly, faster with cache support.

Volley android example and tutotiral HTTP GET

Volley offers the following benefits: 

  • Automatic scheduling of network requests.
  • Multiple concurrent network connections.
  • Transparent disk and memory response caching with standard HTTP cache coherence.
  • Support for request prioritization.
  • Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel.
  • Ease of customization, for example, for retry and back off.
  • Strong ordering makes it easy to correctly populate your UI with data fetched asynchronously from the network.
  • Debugging and tracing tools.

Let’s Build Example of Android Volley Library 

In this “Volley android tutorial,” we are setting volley “Simple Request” and doing JSON parsing. The result will show in TextView only (for better understating).

Step 1. Create an android project in the android studio (Follow this tutorial: Android First Program in Android Studio kotlin)
Step 2. Add Volley Library in your android project.

The easiest way to add Volley to your project is to add the following dependency to your app’s build.gradle file:

build.gradle (Module: app)

dependencies {
    ...
    compile 'com.android.volley:volley:1.1.0'
}
Step 3. Add the INTERNET permission in Manifest.xml file
<manifest>
   ....
   <uses-permission android:name="android.permission.INTERNET" />
</manifest>
Step 4. API, you need to call API

in this example we are using https://api.github.com/search/users?q=eyehunt git hub search API

where JSON response will this format, you have to do JSON parsing.

{
  "total_count": 1,
  "incomplete_results": false,
  "items": [
    {
      "login": "eyehunt",
      "id": 21332347,
      "node_id": "MDQ6VXNlcjIxMzMyMzQ3",
      "avatar_url": "https://avatars3.githubusercontent.com/u/21332347?v=4",
      "gravatar_id": "",
      "url": "https://api.github.com/users/eyehunt",
      "html_url": "https://github.com/eyehunt",
      "followers_url": "https://api.github.com/users/eyehunt/followers",
      "following_url": "https://api.github.com/users/eyehunt/following{/other_user}",
      "gists_url": "https://api.github.com/users/eyehunt/gists{/gist_id}",
      "starred_url": "https://api.github.com/users/eyehunt/starred{/owner}{/repo}",
      "subscriptions_url": "https://api.github.com/users/eyehunt/subscriptions",
      "organizations_url": "https://api.github.com/users/eyehunt/orgs",
      "repos_url": "https://api.github.com/users/eyehunt/repos",
      "events_url": "https://api.github.com/users/eyehunt/events{/privacy}",
      "received_events_url": "https://api.github.com/users/eyehunt/received_events",
      "type": "User",
      "site_admin": false,
      "score": 34.170288
    }
  ]
}
Step 4. Add TextView in main_activity.xml

we are not making complex code to show data in list view. Just for now learn implementation Volley and parsing Json data.

<?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="in.eyehunt.volleyandroidsimplerequest.MainActivity">

    <TextView
        android:textColor="@color/colorPrimary"
        android:textAllCaps="true"
        android:id="@+id/tv_users"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Hello World!"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.051"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.032" />

</android.support.constraint.ConstraintLayout>
Step 4. Add following code and methods in MainActivity.kt

this code in kotlin, For more, know about kotlin android: Kotlin Android basic fundamental codes

package `in`.eyehunt.volleyandroidsimplerequest

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import org.json.JSONArray
import org.json.JSONObject

class MainActivity : AppCompatActivity() {
    private var textView: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        textView = findViewById<TextView>(R.id.tv_users)

        getUsers()
    }

    // function for network call
    fun getUsers() {
        // Instantiate the RequestQueue.
        val queue = Volley.newRequestQueue(this)
        val url: String = "https://api.github.com/search/users?q=eyehunt"

        // Request a string response from the provided URL.
        val stringReq = StringRequest(Request.Method.GET, url,
                Response.Listener<String> { response ->
                    
                    var strResp = response.toString()
                    val jsonObj: JSONObject = JSONObject(strResp)
                    val jsonArray: JSONArray = jsonObj.getJSONArray("items")
                    var str_user: String = ""
                    for (i in 0 until jsonArray.length()) {
                        var jsonInner: JSONObject = jsonArray.getJSONObject(i)
                        str_user = str_user + "\n" + jsonInner.get("login")
                    }
                    textView!!.text = "response : $str_user "
                },
                Response.ErrorListener { textView!!.text = "That didn't work!" })
        queue.add(stringReq)
    }
}
Step 5: Now Run the application, in an emulator or On your Android device

Output screenshot Volley android JSON parsing example android :

Volley android JSON parsing example

Download Volley android JSON parsing example source code  :

https://github.com/EyeHunts/VolleyAndroidSimpleRequest

Note : This example (Project) is developed in Android Studio 3.0.1 ,tested on Android 9 ( Android P), compile SDK version API 26: Android 8.0 (Oreo)

MinSdkVersion=”15″

TargetSdkVersion=”26″

Coding in Kotlin

Google official video must watch for good understanding

6 thoughts on “Volley Android Example JSON Parsing – Kotlin”

  1. I found the problem right. I followed your style. Every time after I have asked you to run normally until today, suddenly there is a problem running. Can you help me answer?

  2. I want to know if my API doesn’t have an Array. How do I fix it to show the object?
    Which I want to show the video

    example

    {
    version: “4.2.6”,
    point_enable: 1,
    point_sum: 0,
    point_progress: 0,
    stream: {
    audio: “http://——————–/———-/———–m3u8”,
    video: “http://——————–/———-/———–.m3u8”,
    },

Leave a Reply

Your email address will not be published. Required fields are marked *