Kotlin Volley JSON Parsing Using URL In Android Example is today’s topic.
We will parse JSON with Volley library in this tutorial.
Volley library makes it easy to fetch the data from remote server in JSON format and to parse this JSON data in the android studio.
This Kotlin JSON Parser example will be able to load data from the MySQL database.
Volley will return JSON data into the String format.
First of all, use the following video to show output.
Volley in Gradle
After making a new project in the android studio, add the following line into the build.gradle(Module:app) file.
implementation 'com.android.volley:volley:1.1.1'
Above line will integrate all the classes and methods of the volley library into our project.
We will be able to use all of them directly into our Kotlin files.
Manifest Updation
Open up your AndroidManifest.xml file and write the following line in it
<uses-permission android:name="android.permission.INTERNET"/>
Above line is giving the permission to use the internet of the android device.
Internet permission is not too much sensitive for user security so we do not need to ask for runtime permission.
Model Making
Create a new Kotlin file and give it a name like PlayerModel.kt
Now write the following source line in the PlayerModel.kt file.
class PlayerModel { var name: String? = null var country: String? = null var city: String? = null var id: String? = null fun getNames(): String { return name.toString() } fun setNames(name: String) { this.name = name } fun getCountrys(): String { return country.toString() } fun setCountrys(country: String) { this.country = country } fun getCitys(): String { return city.toString() } fun setCitys(city: String) { this.city = city } fun getids(): String { return id.toString() } fun setids(id: String) { this.id = id } }
Above file is the model of this tutorial. Model will help us to parse JSON easily.
You can see that there are four string variables ( name, country, city, id ) in the above model class.
For all these four string variable, I have created getter and setter methods.
These getter and setter methods will help us to maintain JSON data in the appropriate manner.
Main XML File
Now in your activity_main.xml file, add the following coding snippet
<?xml version="1.0" encoding="utf-8"?> <LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="40sp" android:textColor="#000" android:text=" below info is fetched from URL With volley"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/tv" android:layout_marginLeft="10dp" android:paddingTop="10dp" android:paddingBottom="10dp" android:textSize="20sp" android:textColor="#000" android:text="" /> </LinearLayout>
Main XML layout file contains two text views.
First text view is static and it will not change it’s value over time.
Second text view will contain the data we fetched from the URL.
We will fill the data inside the text view in the Kotlin file.
Final Kotlin Class
Open up your MainActivity.kt class and add the below source lines in it
import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.TextView import android.widget.Toast import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.Response import com.android.volley.VolleyError import com.android.volley.toolbox.StringRequest import com.android.volley.toolbox.Volley import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.ArrayList class MainActivity : AppCompatActivity() { private val URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php" private var textView: TextView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.tv) requestJSON() } private fun requestJSON() { val stringRequest = StringRequest(Request.Method.GET, URLstring, Response.Listener { response -> Log.d("strrrrr", ">>$response") try { //getting the whole json object from the response val obj = JSONObject(response) if (obj.optString("status") == "true") { val playersModelArrayList = ArrayList<PlayerModel>() val dataArray = obj.getJSONArray("data") for (i in 0 until dataArray.length()) { val playerModel = PlayerModel() val dataobj = dataArray.getJSONObject(i) playerModel.setids(dataobj.getString("id")) playerModel.setNames(dataobj.getString("name")) playerModel.setCountrys(dataobj.getString("country")) playerModel.setCitys(dataobj.getString("city")) playersModelArrayList.add(playerModel) } for (j in playersModelArrayList.indices) { var a : String? = textView!!.text.toString() textView!!.setText( a +"" + playersModelArrayList[j].getids() + " " + playersModelArrayList[j].getNames() + " " + playersModelArrayList[j].getCountrys() + " " + playersModelArrayList[j].getCitys() + " \n" ) } } else { Toast.makeText(this@MainActivity, obj.optString("message") + "", Toast.LENGTH_SHORT).show() } } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { error -> //displaying the error in toast if occurrs Toast.makeText(applicationContext, error.message, Toast.LENGTH_SHORT).show() }) // request queue val requestQueue = Volley.newRequestQueue(this) requestQueue.add(stringRequest) } }
More Knowledge on MainActivity
Now let us see what above class (MainActivity.kt) want to say in detail.
First of all, check out the following code pad
private val URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php" private var textView: TextView? = null
First line is the string variable. This variable holds the URL as it’s value.
This URL will give s some data in the JSON format.
Second line will create one object of the Text view class.
Now inside the onCreate() method, compiler is calling another method named requestJSON()
Following are the coding lines for requestJSON() method.
private fun requestJSON() { val stringRequest = StringRequest(Request.Method.GET, URLstring, Response.Listener { response -> Log.d("strrrrr", ">>$response") try { //getting the whole json object from the response val obj = JSONObject(response) if (obj.optString("status") == "true") { val playersModelArrayList = ArrayList<PlayerModel>() val dataArray = obj.getJSONArray("data") for (i in 0 until dataArray.length()) { val playerModel = PlayerModel() val dataobj = dataArray.getJSONObject(i) playerModel.setids(dataobj.getString("id")) playerModel.setNames(dataobj.getString("name")) playerModel.setCountrys(dataobj.getString("country")) playerModel.setCitys(dataobj.getString("city")) playersModelArrayList.add(playerModel) } for (j in playersModelArrayList.indices) { var a : String? = textView!!.text.toString() textView!!.setText( a +"" + playersModelArrayList[j].getids() + " " + playersModelArrayList[j].getNames() + " " + playersModelArrayList[j].getCountrys() + " " + playersModelArrayList[j].getCitys() + " \n" ) } } else { Toast.makeText(this@MainActivity, obj.optString("message") + "", Toast.LENGTH_SHORT).show() } } catch (e: JSONException) { e.printStackTrace() } }, Response.ErrorListener { error -> //displaying the error in toast if occurrs Toast.makeText(applicationContext, error.message, Toast.LENGTH_SHORT).show() }) // request queue val requestQueue = Volley.newRequestQueue(this) requestQueue.add(stringRequest) }
Look at the first line from the above method.
This is the line where Volley library comes into the picture.
First line is making one StringRequest. Here, method is GET and URL is the string variable called “URLstring”
Now look at the below line which is from the requestJSON() method itself.
val obj = JSONObject(response)
Above line’s obj variable will hold the JSON data in string format.
Now let us see the below JSON data which we are fetching from the URL : https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php
{ "status": "true", "message": "Data fetched successfully!", "data": [ { "id": "1", "name": "Roger Federer", "country": "Switzerland", "city": "Basel", "imgURL": "https://demonuts.com/Demonuts/SampleImages/roger.jpg" }, { "id": "2", "name": "Rafael Nadal", "country": "Spain", "city": "Madrid", "imgURL": "https://demonuts.com/Demonuts/SampleImages/nadal.jpg" }, { "id": "3", "name": "Novak Djokovic", "country": "Serbia", "city": "Monaco", "imgURL": "https://demonuts.com/Demonuts/SampleImages/djoko.jpg" }, { "id": "4", "name": "Andy Murray", "country": "United Kingdom", "city": "London", "imgURL": "https://demonuts.com/Demonuts/SampleImages/murray.jpg" }, { "id": "5", "name": "Maria Sharapova", "country": "Russia", "city": "Moscow", "imgURL": "https://demonuts.com/Demonuts/SampleImages/shara.jpg" }, { "id": "6", "name": "Caroline Wozniacki", "country": "Denmark", "city": "Odense", "imgURL": "https://demonuts.com/Demonuts/SampleImages/woz.jpg" }, { "id": "7", "name": "Eugenie Bouchard", "country": "Canada", "city": " Montreal", "imgURL": "https://demonuts.com/Demonuts/SampleImages/bou.png" }, { "id": "8", "name": "Ana Ivanovic", "country": "Serbia", "city": "Belgrade", "imgURL": "https://demonuts.com/Demonuts/SampleImages/iva.jpg" } ] }
You can see that it has three main parameter : status, message and data
Now see the below line,
if (obj.optString("status") == "true") {
Above line is checking one if condition. It is checking the value of the status parameter of the JSON data.
If the value of the status parameter is true then compiler will go inside the if condition.
After this, compiler will parse the data parameter of JSON response.
Then the Compiler will create one for loop.
In the each iteration of the for loop, compiler will fetch the data and it will use various setter methods from PlayerModel.kt file.
At the end of the for loop, we will have one arraylist which is full of the objects of the PlayerModel.kt file.
After this, compiler will go through another for loop which is as the below
for (j in playersModelArrayList.indices) { var a : String? = textView!!.text.toString() textView!!.setText( a +"" + playersModelArrayList[j].getids() + " " + playersModelArrayList[j].getNames() + " " + playersModelArrayList[j].getCountrys() + " " + playersModelArrayList[j].getCitys() + " \n" ) }
Inside this for loop, compiler will print the JSON response in the Text View.
Here, compiler is using various getter methods from PlayerModel.kt file to get the data stored inside the arraylist.