Saturday, May 12, 2018

Json parsing in android kotlin

Video Demo:


JSON means JavaScript Object Notation. Json parsing is used when our app wants to exchange data with our server. There are alots of tutorial in Json paring in android java But there are limited tutorial of json parsing in android using kotlin. So here I am showing tutorial of Jsonparsing in android Kotlin. Download source code from here


json parsing android kotlin

Add this dependency in your gradle file:

compile 'com.squareup.okhttp3:okhttp:3.8.1'

activity_main.xml:


    



MainActivity.kt:


package com.deepshikha.kotlin.jsonparsing

import android.app.ProgressDialog
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.ListView
import okhttp3.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.IOException
import kotlin.collections.ArrayList

class MainActivity : AppCompatActivity() {

    lateinit var dialog:ProgressDialog
    lateinit var lv_details: ListView

    var al_details:ArrayList = ArrayList();
    val client = OkHttpClient()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        dialog= ProgressDialog.show(this@MainActivity,"Alert","Loading")
        lv_details = findViewById(R.id.lv_details) as ListView
        run("https://api.androidhive.info/contacts/")


    }

    fun run(url: String) {
        dialog.show()
        val request = Request.Builder()
                .url(url)
                .build()

        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                dialog.dismiss()

            }

            override fun onResponse(call: Call, response: Response) {
                var str_response = response.body()!!.string()
                val json_contact:JSONObject = JSONObject(str_response)

                var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")

                var i:Int = 0
                var size:Int = jsonarray_contacts.length()

                al_details= ArrayList();

                for (i in 0.. size-1) {
                    var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)


                    var model:Model= Model();
                    model.id=json_objectdetail.getString("id")
                    model.name=json_objectdetail.getString("name")
                    model.email=json_objectdetail.getString("email")
                    model.address=json_objectdetail.getString("address")
                    model.gender=json_objectdetail.getString("gender")

                    al_details.add(model)


                }

                runOnUiThread {
                    //stuff that updates ui
                    val obj_adapter : CustomAdapter
                    obj_adapter = CustomAdapter(applicationContext,al_details)
                    lv_details.adapter=obj_adapter
                }

                dialog.dismiss()

            }

        })

    }


}

adapter_layout.xml:


    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/ll_main"
    android:background="#e4e2e2"
    android:padding="5dp"
    android:orientation="vertical">

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_name"
        android:textSize="15dp"
        android:layout_margin="5dp"
        android:textColor="#000000"/>

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_email"
        android:layout_margin="5dp"
        android:textSize="15dp"
        android:textColor="#000000"/>

            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_address"
        android:layout_margin="5dp"
        android:textSize="15dp"
        android:textColor="#000000"/>




CustomAdapter.kt:

package com.deepshikha.kotlin.jsonparsing

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

/**
 * Created by deepshikha on 1/11/17.
 */

class CustomAdapter(context: Context,al_details:ArrayList) : BaseAdapter(){

    private val mInflator: LayoutInflater
    private val al_details:ArrayList

    init {
        this.mInflator = LayoutInflater.from(context)
        this.al_details=al_details
    }

    override fun getCount(): Int {
        return al_details.size
    }

    override fun getItem(position: Int): Any {
        return al_details.get(position)
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        val view: View?
        val vh: ListRowHolder
        if (convertView == null) {
            view = this.mInflator.inflate(R.layout.adapter_layout, parent, false)
            vh = ListRowHolder(view)
            view.tag = vh
        } else {
            view = convertView
            vh = view.tag as ListRowHolder
        }

        vh.tv_name.text = al_details.get(position).name
        vh.tv_email.text = al_details.get(position).email
        vh.tv_address.text = al_details.get(position).address
        if (position%2==0) {
            vh.ll_main.setBackgroundColor(Color.parseColor("#e4e2e2"))
        }else{
            vh.ll_main.setBackgroundColor(Color.parseColor("#FFFFFF"))

        }
        return view
    }
}

private class ListRowHolder(row: View?) {
    public val tv_name: TextView
    public val tv_email: TextView
    public val tv_address: TextView
    public val ll_main: LinearLayout

    init {
        this.tv_name = row?.findViewById(R.id.tv_name) as TextView
        this.tv_email = row?.findViewById(R.id.tv_email) as TextView
        this.tv_address = row?.findViewById(R.id.tv_address) as TextView
        this.ll_main = row?.findViewById(R.id.ll_main) as LinearLayout
    }


} 

Model.kt:


package com.deepshikha.kotlin.jsonparsing

/**
 * Created by deepshikha on 31/10/17.
 */
public class Model{
    lateinit var id:String
    lateinit var name:String
    lateinit var email:String
    lateinit var address:String
    lateinit var gender:String

    constructor(id: String,name:String,email:String,address:String,gender:String) {
        this.id = id
        this.name = name
        this.email = email
        this.address = address
        this.gender = gender
    }

    constructor()


}

No comments:

Post a Comment