JSON Parsing in Android Using Volley Library with Kotlin
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the implementation of JsonObject using Volley in Android using Kotlin. We will be creating a simple application in which we will be parsing the data from a URL using the Volley library in Kotlin.
Note: If you are looking to parse the JSON data using the Volley library in Android using Java. Check out the following article: JSON Parsing in Android using Volley Library in Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Add the below dependency in your build.gradle file
Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.
// below line is used for volley library implementation ‘com.android.volley:volley:1.2.0’ // below line is used for image loading library implementation ‘com.squareup.picasso:picasso:2.71828’
After adding this dependency sync your project and now move towards the AndroidManifest.xml part.
Step 3: Adding permissions to the internet in the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it.
XML
<!--permissions for INTERNET--> < uses-permission android:name = "android.permission.INTERNET" /> |
Step 4: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> <!--on below line we are creating a swipe to refresh layout--> < ScrollView android:layout_width = "match_parent" android:layout_height = "match_parent" android:fillViewport = "true" android:orientation = "vertical" tools:context = ".MainActivity" > < RelativeLayout android:id = "@+id/container" android:layout_width = "match_parent" android:layout_height = "match_parent" > <!--on below line we are creating a simple card view--> < LinearLayout android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_above = "@id/idBtnVisitCourse" android:orientation = "vertical" > <!--on below line we are creating a image view--> < ImageView android:id = "@+id/idIVCourse" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_marginBottom = "5dp" /> <!--on below line we are creating our text view--> < TextView android:id = "@+id/idTVCourseName" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "4dp" android:padding = "4dp" android:textColor = "@color/black" android:textSize = "20sp" android:textStyle = "bold" /> <!--on below line we are creating one more text view--> < TextView android:id = "@+id/idTVPreq" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_margin = "4dp" android:padding = "4dp" android:textColor = "@color/black" android:textStyle = "bold" /> <!--on below line we are creating a text view for description--> < TextView android:id = "@+id/idTVDesc" android:layout_width = "match_parent" android:layout_height = "match_parent" android:layout_margin = "4dp" android:padding = "4dp" android:textColor = "@color/black" /> </ LinearLayout > <!--on below line we are creating a progress bar--> < ProgressBar android:id = "@+id/idLoadingPB" android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:layout_centerInParent = "true" android:visibility = "visible" /> <!--on below line we are creating a button to visit our course--> < Button android:id = "@+id/idBtnVisitCourse" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:layout_alignParentBottom = "true" android:layout_margin = "4dp" android:padding = "3dp" android:text = "Visit Course" android:textAllCaps = "false" android:visibility = "gone" /> </ RelativeLayout > </ ScrollView > |
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
package com.gtappdevelopers.kotlingfgproject import android.content.Intent import android.net.Uri import android.os.Bundle import android.util.Log import android.view.View import android.widget.* import androidx.appcompat.app.AppCompatActivity import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.JsonObjectRequest import com.android.volley.toolbox.Volley import com.squareup.picasso.Picasso class MainActivity : AppCompatActivity() { // on below line we are creating variables // for our text view, image view and progress bar lateinit var courseNameTV: TextView lateinit var courseDescTV: TextView lateinit var courseReqTV: TextView lateinit var courseIV: ImageView lateinit var visitCourseBtn: Button lateinit var loadingPB: ProgressBar // on below line we are creating a variable for our url. override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) // on below line we are initializing our variable with their ids. courseNameTV = findViewById(R.id.idTVCourseName) courseDescTV = findViewById(R.id.idTVDesc) courseReqTV = findViewById(R.id.idTVPreq) courseIV = findViewById(R.id.idIVCourse) visitCourseBtn = findViewById(R.id.idBtnVisitCourse) loadingPB = findViewById(R.id.idLoadingPB) // on below line we are creating a variable for our // request queue and initializing it. val queue: RequestQueue = Volley.newRequestQueue(applicationContext) // on below line we are creating a variable for request // and initializing it with json object request val request = JsonObjectRequest(Request.Method.GET, url, null , { response -> // this method is called when we get a successful response from API. // we are setting the visibility of progress bar as gone. loadingPB.setVisibility(View.GONE) // on below line we are adding a try catch block. try { // on below line we are getting data from our response // and setting it in variables. val courseName: String = response.getString( "courseName" ) val courseLink: String = response.getString( "courseLink" ) val courseImg: String = response.getString( "courseimg" ) val courseDesc: String = response.getString( "courseDesc" ) val coursePreq: String = response.getString( "Prerequisites" ) // on below line we are setting our // data to our text view and image view. courseReqTV.text = coursePreq courseDescTV.text = courseDesc courseNameTV.text = courseName // on below line we are setting // image view from image url. Picasso.get().load(courseImg).into(courseIV) // on below line we are changing // visibility for our button. visitCourseBtn.visibility = View.VISIBLE // on below line we are adding // click listener for our button. visitCourseBtn.setOnClickListener { // on below line we are opening // a intent to view the url. val i = Intent(Intent.ACTION_VIEW) i.setData(Uri.parse(courseLink)) startActivity(i) } } catch (e: Exception) { // on below line we are // handling our exception. e.printStackTrace() } }, { error -> // this method is called when we get // any error while fetching data from our API Log.e( "TAG" , "RESPONSE IS $error" ) // in this case we are simply displaying a toast message. Toast.makeText( this @MainActivity , "Fail to get response" , Toast.LENGTH_SHORT) .show() }) // at last we are adding // our request to our queue. queue.add(request) } } |
Now run your application to see the output of it.
Output: