How to call webservice from kotlin in android

Step 1:

  1. create new application on Android Studio 3.0
  2. Create GUI  textView, button and progress bar
  3. Add some external library
  4. create kotlin data class
  5. define your webservice url in MainActivity.kt
  6. add internet uses permission your mainfest.xml file

MainActivity.kt

package com.iotwebplanet.learn.myapplication1

import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.util.Base64
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.TextView
import java.net.HttpURLConnection
import java.net.URL
import android.os.StrictMode
import android.widget.ProgressBar
import com.beust.klaxon.*
import com.github.salomonbrys.kotson.fromJson
import com.google.gson.Gson



class MainActivity : AppCompatActivity() {

    public fun parse(name: String):Unit {
        val cls = Parser::class.java
        cls.getResourceAsStream(name)?.let { inputStream ->
            return (Parser().parse(inputStream) as Unit?)!!
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {

        //Thread policy for internet access
        val SDK_INT = android.os.Build.VERSION.SDK_INT
        if (SDK_INT > 8) {
            val policy = StrictMode.ThreadPolicy.Builder()
                    .permitAll().build()
            StrictMode.setThreadPolicy(policy)


        }
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)

//kotlin typecasting of view

        val button=findViewById(R.id.button) as Button
        var tv=findViewById(R.id.mytext) as TextView
        val progress_bar=findViewById(R.id.progressBar) as ProgressBar

//on button click event

        button.setOnClickListener({
            tv.setText("Clicked");
            progress_bar.visibility = View.VISIBLE

// Kotlin + HttpURLConnection

            val connection = URL("example.com").openConnection() as HttpURLConnection
            connection.connect()
            println(connection.responseCode)
            println(connection.getHeaderField("Content-Type"))
            val text = connection.inputStream.use { it.reader().use { reader -> reader.readText() } }

//suppose sample data from http get calls
/*
            [
            {"sku":"00012","position":1,"category_id":"6"},
            {"sku":"00077","position":1,"category_id":"6"},
            {"sku":"00072","position":1,"category_id":"6"},
            {"sku":"00032","position":1,"category_id":"6"},
            {"sku":"00074","position":1,"category_id":"6"},
            {"sku":"00078","position":1,"category_id":"6"}
            ]

*/
            println(text)   //sample data output
            //setting text in txt view for demo.
            tv.setText(text)

//optional block
//response to pojo work . following statement may be different in your case plz do as per your data
            val gson = Gson()        //gson object
            val list1 = gson.fromJson<List<Product>>(text) //convert/store response data to kotlin data class Product

println("Saved Data "+list1.size)   //how much data saved
            val s=list1.size;   //size of collection
//printing saved data in pojo class
            for (i in 0..s-1) {
                //printing list from loop
                println("Products Data : $list1.get(i).sku $list1.get(i).position $list1.get(i).category_id")

            }
// end of optional block

            progress_bar.visibility = View.GONE;  //hide progress bar

        })   //end of button event

    }



    //optional code not related to tutorial
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_main, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item.itemId

        if (id == R.id.action_settings) {
            return true
        }

        return super.onOptionsItemSelected(item)
    }
}

Mainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iotwebplanet.learn.myapplication1">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

    <application android:allowBackup="true" android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true" android:theme="@style/AppTheme">
        <activity android:name=".MainActivity" android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

Product.kt .  data class(optional)

package com.iotwebplanet.learn.myapplication1
/**
 * Created by developer on 10/06/17.
 */
data class Product(val sku: String, val position: Int, var category_id: Int)

Important to add in Build.Gradle(Module:app)

compile 'com.beust:klaxon:0.30'
compile 'com.github.salomonbrys.kotson:kotson:2.5.0'

 

How to Transfer Data between Android Activity using Kotlin

Here is i am describing how to transfer variable or value from one  Activity to Another Activity in Android Application.I am using Android Studio 3.0.I hope my code will help you. You can use this code in button event or any other place where it is required.

Set Data in Activity

val myvalue="I am from Main Activity"
val myActivity = Intent(applicationContext, Another_activity::class.java) //name of activity to launch 
  myActivity.putExtra("value",myvalue) // value will save of your myvalue variable used for another activity
   startActivity(myActivity) //to launch another activity

Get Data from Activity

//create this code in Another_activity.kt
//getting/fetch Intent value
     val data = intent.extras.getString("value")
    //Now its your choice whatever you want to do with data.

feel free to comment and feedback

Good bye findViewById() use Kotlin Android Extensions

Hi Developers as we always juggle with findViewById() in Android activity class . Some time we forget to typecast xml into Kotlin or java . So good news for Kotlin android developer.

Kotlin Android Extensions

Kotlin Android Extensions are another Kotlin plugin that is included in the regular one, and that will allow to recover/find views from Fragments, Activities,   and Views in an effective  way.

see how easy it is ….

Step 1.

Add Kotlin Android Extensions in Gradle (Project)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions' //this the main plugin

And that’s all you need to sync your gradle. You’re now ready to start working with it.

Step2.

Recovering/find views in an Activity or Fragment

import your xml layout like below code in activity . here my activity xml file name is activity_main it would be different in your case. so add it in your activitity.

import kotlinx.android.synthetic.main.activity_main.*

The code that the plugin generates is able to store a view cache, so if you ask the view again, this won’t require another findViewById.

Simple Call Xml View by name .

textView.setText("Msg")

Here textView is my text view component inside xml.