How to call webservice from kotlin in android
Step 1:
- create new application on Android Studio 3.0
- Create GUI textView, button and progress bar
- Add some external library
- create kotlin data class
- define your webservice url in MainActivity.kt
- 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="https://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'
Leave a Reply
You must be logged in to post a comment.