Showing posts with label Kotlin. Show all posts

YouTube Player API in Android using Kotlin

Introduction:

In this article, we will learn how to integrate and play a video using YouTube API in Android with Kotlin.

YouTube Android Player API enables developers to incorporate or integrate video playback functionality into our own developed Android applications. Using this API, we can load and cue play videos. It has a built in play controls for controlling the video playback actions such as Play, Pause or Seek to a specific time/point in the current video. Our Android Phone must have the YouTube app. Because this API interact with service that is a part of YouTube app.

Before going to coding part, we need to follow below steps for setup the YouTube API in our own developed app

  1. Download YouTube API client library from the following link, basically this library is a jar file. https://developers.google.com/youtube/android/player/downloads/
  2. Register our app in Google API console & Enable YouTube Android Player API in Google API Console. In this way we will obtain an Android API key, which is must for using this API. https://console.developers.google.com/apis/

Register app and get Android API Key:

  1. Open Google API Console.
  2. Create a new project or choose your existing project in API Console.
  3. Open API page and search for YouTube Android Player API.
  4. Then select enable API and go to credentials page.
  5. Then select API Key will creates your API key. We can improve the security of the API key with package name & SHA-1 key of your system.

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2: Setting up YouTube Library and Manifest:

In this part, we will see how to setup the YouTube API Client library for the project.

  1. With respect to our previous step, we have already downloaded the API client library for YouTube API as a Zip file.
  2. Then extract the jar files and add them to “libs” folder.
  3. Then open app level build.gradle file and add the following lines in dependencies.
    dependencies { 
       …
       implementation files('libs/YouTubeAndroidPlayerApi.jar')   
        …
    }
  4. Then click “Sync Now” to setup your project.
  5. Now the project is ready and add internet permissions in AndroidManifest.xml.
    <uses-permission android:name="android.permission.INTERNET"/>

Step 3: Integration of YouTube Android Player in Screen using Kotlin:

In this step, we will learn how to embed YouTube Android Player & how to play a particular video (by its id).

  1. Open your layout file and in my case I am using “activity_main.xml” and included the “YouTubePlayerView” as like below.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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"
        tools:context="com.androidmad.ytubeapi.MainActivity">
    
        <com.google.android.youtube.player.YouTubePlayerView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:id="@+id/yt_pv"/>
    
    </android.support.constraint.ConstraintLayout>
  2. We need to initialize & load the video to YouTubePlayerView. So, open or create an activity file. In my case I am using “MainActivity.kt”.
  3. To initialize the YouTube Player add the implementation of “YouTubePlayer.OnInitializedListener” as like below.
  4. YouTubePlayer is initialized by calling Initialize method with Android API key and its initialization listener.
    class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {
    
        override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
        }
    
        override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {
        }
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            yt_pv.initialize(DeveloperApiKey, this)
        }
    }
    Here, DeveloperApiKey – a variable for Android API Key. In Kotlin, we can directly access the view in design or layout file from code behind using kotlinx for Android
  5. We can load or cue the YouTube video by its id after the YouTube Player initialized successfully like below
    override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
     showShortToast("Youtube Api Initialization Success")
     if (!wasRestored) {
      player?.cueVideo("wKJ9KzGQq0w");
     }
    }
    Here, showShortToast is an extension method created to Show Toast with short duration. To know about extensions, please read my previous article on Kotlin.

Full Code:

You can find the full code implementation of the Activity here.

class MainActivity : YouTubeBaseActivity(), YouTubePlayer.OnInitializedListener {

    override fun onInitializationSuccess(provider: YouTubePlayer.Provider?, player: YouTubePlayer?, wasRestored: Boolean) {
        showShortToast("Youtube Api Initialization Success")
        if (!wasRestored) {
            player?.cueVideo("wKJ9KzGQq0w");
        }
    }

    override fun onInitializationFailure(p0: YouTubePlayer.Provider?, p1: YouTubeInitializationResult?) {
        showShortToast("Youtube Api Initialization Failure")
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        yt_pv.initialize("API KEY", this)
    }
}

Reference:

YouTube Android Player API https://developers.google.com/youtube/android/player/
YouTube API Client Library Downloads https://developers.google.com/youtube/android/player/downloads/
Kotlin Extensions (Previous Article) https://www.androidmads.info/2019/06/how-to-use-extensions-method-in-kotlin.html
Extensions in Kotlin https://kotlinlang.org/docs/reference/extensions.html

If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.


Verify OTP without SMS permission in Android using Kotlin

Introduction:

Google have updated the policy in Google Developer Blog about user privacy and security. As per the policy, we must remove SMS and Call Log permissions from manifest or else our app will be removed from google play store. But our app needs SMS permission for automatically authenticate app users. What is the solution?
Google offers an API named as SMS Retriever API to allow our app to read SMS without SMS permission and we need to follow a set of rules while formatting the verification message. In this article, we will learn how to use SMS Retriever API in Kotlin to read SMS and rules need to be followed. If you are new to Kotlin, read my previous articles to read Kotlin from scratch.

Verification Message Format:

We should follow the below rules while formatting verification message.

  1. Message should have maximum of 140 bytes length.
  2. Should start with “<#>”.
  3. Followed by OTP - One Time Pass (code/word).
  4. 11 character length hash for the app (it is generated by our app).
Example:
<#> Your Example App code is: 123ABC78 
FA+9qCX9VSu

Coding Part:

I have detailed the article as in the following steps.
Step 1: Creating New Project with Empty Activity.
Step 2: Setting up the Google Auth Libraries.
Step 3: Implementation of SMS Retriever API using Kotlin.

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2: Setting up the Google Auth Libraries:

In this part, we will see how to setup the library for the project.

  1. Then add the following lines in app level build.gradle file to apply google services to your project.
    dependencies { 
       …
        implementation 'com.google.android.gms:play-services-base:11.6.0'
        implementation 'com.google.android.gms:play-services-auth-api-phone:11.6.0'
        …
    }
    
  2. Then click “Sync Now” to setup your project.
  3. Now the project is ready and no need to add any permissions in Manifest.

Step 3: Implementation of SMS Retriever API using Kotlin:

Create user interface to display your OTP read through the API. Open or create “activity_main.xml” and paste the following code snippet.

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.androidmad.smsretrieverapisample.MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:onClick="onBtnResendClick"
        android:id="@+id/btn_restart"
        android:text="Resend"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@id/editText"
        app:layout_constraintVertical_bias="0.247" />

</android.support.constraint.ConstraintLayout>

We need to create a helper class to provide the hash value for our app to construct the verification message. Create a Kotlin class file named as “AppSignatureHelper.kt” and paste following code snippet which is helpful to create 11 character length hash for our application.

package com.androidmad.smsretrieverapisample

import android.annotation.SuppressLint
import android.content.Context
import android.content.ContextWrapper
import android.content.pm.PackageManager
import android.os.Build
import android.support.annotation.RequiresApi
import android.util.Base64
import android.util.Log
import java.nio.charset.StandardCharsets
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.*

class AppSignatureHelper(context: Context) : ContextWrapper(context) {

    /**
     * Get all the app signatures for the current package
     *
     * @return
     */
    // Get all package signatures for the current package
    // For each signature create a compatible hash
    val appSignatures: ArrayList
        @SuppressLint("PackageManagerGetSignatures")
        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        get() {
            val appCodes = ArrayList()

            try {
                val packageName = packageName
                val packageManager = packageManager
                val signatures = packageManager.getPackageInfo(packageName,
                        PackageManager.GET_SIGNATURES).signatures
                signatures
                        .mapNotNull { hash(packageName, it.toCharsString()) }
                        .mapTo(appCodes) { String.format("%s", it) }
            } catch (e: PackageManager.NameNotFoundException) {
                Log.v(TAG, "Unable to find package to obtain hash.", e)
            }

            return appCodes
        }

    companion object {
        val TAG = AppSignatureHelper::class.java.simpleName!!
        private val HASH_TYPE = "SHA-256"
        private val NUM_HASHED_BYTES = 9
        private val NUM_BASE64_CHAR = 11

        @RequiresApi(api = Build.VERSION_CODES.KITKAT)
        private fun hash(packageName: String, signature: String): String? {
            val appInfo = packageName + " " + signature
            try {
                val messageDigest = MessageDigest.getInstance(HASH_TYPE)
                messageDigest.update(appInfo.toByteArray(StandardCharsets.UTF_8))
                var hashSignature = messageDigest.digest()

                // truncated into NUM_HASHED_BYTES
                hashSignature = Arrays.copyOfRange(hashSignature, 0, NUM_HASHED_BYTES)
                // encode into Base64
                var base64Hash = Base64.encodeToString(hashSignature, Base64.NO_PADDING or Base64.NO_WRAP)
                base64Hash = base64Hash.substring(0, NUM_BASE64_CHAR)

                Log.v(TAG + "sms_sample_test", String.format("pkg: %s -- hash: %s", packageName, base64Hash))
                return base64Hash
            } catch (e: NoSuchAlgorithmException) {
                Log.v(TAG + "sms_sample_test", "hash:NoSuchAlgorithm", e)
            }

            return null
        }
    }
}

Then we need to get the hash from the class by creating an object for the helper class and call the hash creation method which returns the value.

// This code requires one time to get Hash keys do comment and share key
val appSignature = AppSignatureHelper(this)
Log.v("AppSignature", appSignature.appSignatures.toString())

Then create a Custom BroadCastReceiver class named as “MySMSBroadcastReceiver.kt” and add the following code snippets.

class MySMSBroadcastReceiver : BroadcastReceiver() {

    private var otpReceiver: OTPReceiveListener? = null

    fun initOTPListener(receiver: OTPReceiveListener) {
        this.otpReceiver = receiver
    }

    override fun onReceive(context: Context, intent: Intent) {
        if (SmsRetriever.SMS_RETRIEVED_ACTION == intent.action) {
            val extras = intent.extras
            val status = extras!!.get(SmsRetriever.EXTRA_STATUS) as Status

            when (status.statusCode) {
                CommonStatusCodes.SUCCESS -> {
                    // Get SMS message contents
                    var otp: String = extras.get(SmsRetriever.EXTRA_SMS_MESSAGE) as String
                    Log.d("OTP_Message", otp)
                    // Extract one-time code from the message and complete verification
                    // by sending the code back to your server for SMS authenticity.
                    // But here we are just passing it to MainActivity
                    if (otpReceiver != null) {
                        otp = otp.replace("<#> ", "").split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[0]
                        otpReceiver!!.onOTPReceived(otp)
                    }
                }

                CommonStatusCodes.TIMEOUT ->
                    // Waiting for SMS timed out (5 minutes)
                    // Handle the error ...
                    if (otpReceiver != null)
                        otpReceiver!!.onOTPTimeOut()
            }
        }
    }

    interface OTPReceiveListener {

        fun onOTPReceived(otp: String)

        fun onOTPTimeOut()
    }
}

Here, OTPReceiveListener is an interface used to call back the events from broad cast receiver. Then open your Activity and implement OTPReceiverListener.

Register the receiver in AndroidManifest.xml with SMS_RETRIEVED action.

<receiver android:name=".MySMSBroadcastReceiver" android:exported="true">
 <intent-filter>
  <action android:name="com.google.android.gms.auth.api.phone.SMS_RETRIEVED" />
 </intent-filter>
</receiver>

Then start the SmsRetriever API as shown in below. Also, register your broadcast receiver with SmsRetriever.SMS_RETRIEVED_ACTION using intent filter.

private fun startSMSListener() {
 try {
  smsReceiver = MySMSBroadcastReceiver()
  smsReceiver!!.initOTPListener(this)

  val intentFilter = IntentFilter()
  intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION)
  this.registerReceiver(smsReceiver, intentFilter)

  val client = SmsRetriever.getClient(this)

  val task = client.startSmsRetriever()
  task.addOnSuccessListener {
   // API successfully started
  }

  task.addOnFailureListener {
   // Fail to start API
  }
 } catch (e: Exception) {
  e.printStackTrace()
 }

}
You will receive OTP in call back methods implemented in you Activity:
override fun onOTPReceived(otp: String) {
 //showToast("OTP Received: " + otp)
 editText.setText(otp)
 if (smsReceiver != null) {
  LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
 }
}

override fun onOTPTimeOut() {
 showToast("OTP Time out")
}

Full Code:

You can find the full code implementation of the Activity here.

class MainActivity : AppCompatActivity(), OTPReceiveListener {

    private var smsReceiver: MySMSBroadcastReceiver? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startSMSListener()
    }


    /**
     * Starts SmsRetriever, which waits for ONE matching SMS message until timeout
     * (5 minutes). The matching SMS message will be sent via a Broadcast Intent with
     * action SmsRetriever#SMS_RETRIEVED_ACTION.
     */
    private fun startSMSListener() {
        try {
            smsReceiver = MySMSBroadcastReceiver()
            smsReceiver!!.initOTPListener(this)

            val intentFilter = IntentFilter()
            intentFilter.addAction(SmsRetriever.SMS_RETRIEVED_ACTION)
            this.registerReceiver(smsReceiver, intentFilter)

            val client = SmsRetriever.getClient(this)

            val task = client.startSmsRetriever()
            task.addOnSuccessListener {
                // API successfully started
            }

            task.addOnFailureListener {
                // Fail to start API
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

    }

    fun onBtnResendClick(view: View){
        startSMSListener()
    }

    override fun onOTPReceived(otp: String) {
        //showToast("OTP Received: " + otp)
        editText.setText(otp)
        if (smsReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
        }
    }

    override fun onOTPTimeOut() {
        showToast("OTP Time out")
    }


    override fun onDestroy() {
        super.onDestroy()
        if (smsReceiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(smsReceiver)
        }
    }


    private fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }
}

Reference:

SMS Retriever API for Android https://developers.google.com/identity/sms-retriever/overview
Google Announcement on Security Policy https://android-developers.googleblog.com/2019/01/reminder-smscall-log-policy-changes.html

If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How to use Extensions method in Kotlin


Introduction:

In this article, we will learn how to create & use extensions for Android development using Kotlin. We have read about Kotlin for Android development. If you are new to Kotlin, read my previous article on Kotlin.

Hello World Android Application Using Kotlin

Extensions:

Kotlin, similar to C# and Gosu, provides the ability to extend a class with new functionality without having to inherit from the class or use any type of design pattern such as Decorator. This is done via special declarations called extensions.

Coding Part:

I have detailed the article as in the following steps.

  1. Creating New Project with Kotlin
  2. Creating Extensions in Kotlin
  3. Implementation of Extension in Kotlin

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2: Creating Extensions in Kotlin

In this part, we will see how to create an extensions for Kotlin.

  1. To declare an extensions function, we need to prefix its name with a receiver type, i.e. the type being extended. The following adds a swap function to MutableList
    fun MutableList<Int>.swap(index1: Int, index2: Int) {
        val tmp = this[index1] // 'this' corresponds to the list
        this[index1] = this[index2]
        this[index2] = tmp
    }
  2. We will take an example to show Toast with Short duration. Traditionally, the Toast is shown like below
    Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
  3. We can simplifies this by the using extensions in Kotlin.
  4. Create a Kotlin file named as “Extensions.kt”. Then add the following code part.
    fun Context.showShortToast(message: CharSequence) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    Here, the base or receiver type of toast is “Context”. So, we have created a function prefixed with “Context”.
  5. In the same way, I have created an extensions to show “Toast with Long duration” and “Alert Dialog with single option”. You can find the full code below.
    package com.androidmad.ktextensions
    
    import android.content.Context
    import android.support.v7.app.AlertDialog
    import android.support.v7.app.AppCompatActivity
    import android.view.View
    import android.widget.Toast
    
    fun Context.showShortToast(message: CharSequence) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }
    
    fun Context.showLongToast(message: CharSequence) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
    }
    
    fun AppCompatActivity.showAlert(title: CharSequence, message: CharSequence) {
        val builder = AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("Ok", { dialog, which ->
                })
    
        val dialog: AlertDialog = builder.create()
        dialog.show()
    }

Step 3: Implementation of Extension in Kotlin

In this section, we will see how to call the above created extensions method in android.

  1. Create a layout file named as “activity_main.xml” and add the following code snippets.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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"
        tools:context="com.androidmad.ktextensions.MainActivity"
        tools:layout_editor_absoluteY="81dp">
    
        <Button
            android:id="@+id/btn_short"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="128dp"
            android:text="Show Short Toast"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <Button
            android:id="@+id/btn_long"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="208dp"
            android:text="Show Long Toast"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    
        <Button
            android:id="@+id/btn_alert"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="92dp"
            android:text="Show Alert Dialog"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
    
    </android.support.constraint.ConstraintLayout>
  2. The output of the layout file looks like below
  3. We have three buttons in our screen to show Toast with Short duration, Long duration and Alert dialog with single option. Open your MainActivity.kt add click listeners for the buttons.
    // Toast with Short Duration
    showShortToast("Show Short Toast using extensions method")
    // Toast with Long Duration
    showLongToast("Show Long Toast using extensions method")
    // Alert Dialog with Single Option
    showAlert("Android Extensions method", "Show Alert Dialog")
  4. Full code of the MainActivity.kt below.
    package com.androidmad.ktextensions
    
    import android.support.v7.app.AppCompatActivity
    import android.os.Bundle
    import kotlinx.android.synthetic.main.activity_main.*
    
    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            btn_short.setOnClickListener({
                showShortToast("Show Short Toast using extensions method")
            })
    
            btn_long.setOnClickListener({
                showLongToast("Show Long Toast using extensions method")
            })
    
            btn_alert.setOnClickListener({
                showAlert("Android Extensions method", "Show Alert Dialog")
            })
    
        }
    
    }

Reference:

Extensions in Kotlin https://kotlinlang.org/docs/reference/extensions.html

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How To Use Retrofit 2 With Android Using Kotlin

Introduction 

Here, I have created a Weather App to demonstrate Retrofit 2 with Kotlin. The same example was created for my previous article “How to Create Weather App Using Retrofit 2 in Android”. You can read my previous article here.

Coding Part 

I have detailed the article in the following sections. 
  1. Creating a new project with Empty activity. 
  2. Setting up the Retrofit HTTP Library and Manifest. 
  3. Implementation of Retrofit with Kotlin.

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2 - Setting up the Retrofit HTTP Library and Manifest

The following lines are added to your Kotlin project by default.
dependencies {   
    …  
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version'  
    implementation 'com.squareup.retrofit2:retrofit:2.0.0'  
    implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
    …  
}
And also, we need to add the INTERNET permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

Step 3 - Implementation of Retrofit with Kotlin

The following API link is used to get the current weather report with respect to the geo-coordinates. The sample API link is here. To know, “How to setting up the Open Weather API”, visit my previous article link. Let's see how to use the link to access the weather data.
  1. Create an interface file named as “WeatherService.kt” and add the following lines in it.
    interface WeatherService {  
        @GET("data/2.5/weather?")  
        fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call  
    }
  2. Create a class file named as “WeatherResponse.kt” and add the following lines. Here, we used a Gson Converter and so the JSON response is automatically converted to the respective and the converter will compare the response tree with the serialized name.
    class WeatherResponse {  
      
        @SerializedName("coord")  
        var coord: Coord? = null  
        @SerializedName("sys")  
        var sys: Sys? = null  
        @SerializedName("weather")  
        var weather = ArrayList()  
        @SerializedName("main")  
        var main: Main? = null  
        @SerializedName("wind")  
        var wind: Wind? = null  
        @SerializedName("rain")  
        var rain: Rain? = null  
        @SerializedName("clouds")  
        var clouds: Clouds? = null  
        @SerializedName("dt")  
        var dt: Float = 0.toFloat()  
        @SerializedName("id")  
        var id: Int = 0  
        @SerializedName("name")  
        var name: String? = null  
        @SerializedName("cod")  
        var cod: Float = 0.toFloat()  
    }  
      
    class Weather {  
        @SerializedName("id")  
        var id: Int = 0  
        @SerializedName("main")  
        var main: String? = null  
        @SerializedName("description")  
        var description: String? = null  
        @SerializedName("icon")  
        var icon: String? = null  
    }  
      
    class Clouds {  
        @SerializedName("all")  
        var all: Float = 0.toFloat()  
    }  
      
    class Rain {  
        @SerializedName("3h")  
        var h3: Float = 0.toFloat()  
    }  
      
    class Wind {  
        @SerializedName("speed")  
        var speed: Float = 0.toFloat()  
        @SerializedName("deg")  
        var deg: Float = 0.toFloat()  
    }  
      
    class Main {  
        @SerializedName("temp")  
        var temp: Float = 0.toFloat()  
        @SerializedName("humidity")  
        var humidity: Float = 0.toFloat()  
        @SerializedName("pressure")  
        var pressure: Float = 0.toFloat()  
        @SerializedName("temp_min")  
        var temp_min: Float = 0.toFloat()  
        @SerializedName("temp_max")  
        var temp_max: Float = 0.toFloat()  
    }  
      
    class Sys {  
        @SerializedName("country")  
        var country: String? = null  
        @SerializedName("sunrise")  
        var sunrise: Long = 0  
        @SerializedName("sunset")  
        var sunset: Long = 0  
    }  
      
    class Coord {  
        @SerializedName("lon")  
        var lon: Float = 0.toFloat()  
        @SerializedName("lat")  
        var lat: Float = 0.toFloat()  
    }
  3. Then, open your Activity file and in my case, I have opened my MainActivity.kt file. Then, create Retrofit Builder with Base URL and GsonConverterFactory.
    val retrofit = Retrofit.Builder()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
  4. Then, create a service for Retrofit with your service interface, as shown below.
    val retrofit = Retrofit.Builder()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
    Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
  5. Then, create a queue with Weather Response which is used to de-serialize the JSON output of the Open Weather API. The following will show the created queue.
    call.enqueue(object : Callback {  
                override fun onResponse(call: Call, response: Response) {  
                    if (response.code() == 200) {  
                        …  
                    }  
                }  
                override fun onFailure(call: Call, t: Throwable) {  
                    …  
            }  
       })

Full Code

You can find the full code implementation of the app here.
class MainActivity : AppCompatActivity() {    
    private var weatherData: TextView? = null    
    override fun onCreate(savedInstanceState: Bundle?) {    
        super.onCreate(savedInstanceState)    
        setContentView(R.layout.activity_main)    
        weatherData = findViewById(R.id.textView)    
        findViewById(R.id.button).setOnClickListener { getCurrentData() }    
    }    
    internal fun getCurrentData() {    
        val retrofit = Retrofit.Builder()    
                .baseUrl(BaseUrl)    
                .addConverterFactory(GsonConverterFactory.create())    
                .build()    
        val service = retrofit.create(WeatherService::class.java)    
        val call = service.getCurrentWeatherData(lat, lon, AppId)    
        call.enqueue(object : Callback {    
            override fun onResponse(call: Call, response: Response) {    
                if (response.code() == 200) {    
                    val weatherResponse = response.body()!!    
    
                    val stringBuilder = "Country: " +    
                            weatherResponse.sys!!.country +    
                            "\n" +    
                            "Temperature: " +    
                            weatherResponse.main!!.temp +    
                            "\n" +    
                            "Temperature(Min): " +    
                            weatherResponse.main!!.temp_min +    
                            "\n" +    
                            "Temperature(Max): " +    
                            weatherResponse.main!!.temp_max +    
                            "\n" +    
                            "Humidity: " +    
                            weatherResponse.main!!.humidity +    
                            "\n" +    
                            "Pressure: " +    
                            weatherResponse.main!!.pressure    
    
                    weatherData!!.text = stringBuilder    
                }    
            }    
    
            override fun onFailure(call: Call, t: Throwable) {    
                weatherData!!.text = t.message    
            }    
        })    
    }    
    companion object {    
    
        var BaseUrl = "http://api.openweathermap.org/"    
        var AppId = "2e65127e909e178d0af311a81f39948c"    
        var lat = "35"    
        var lon = "139"    
    }    
}

Reference

  1. https://square.github.io/retrofit/ 
  2. https://openweathermap.org/api 
  3. https://developer.android.com/kotlin/ 
If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How To Add Download Listener To WebView In Kotlin

Introduction 

In this article, we will learn how to add a download listener to the download files from WebView in Android using Kotlin.

Coding Part

I have divided the coding part into 3 steps as shown in the following.
  1. Creating a new project with Kotlin support. 
  2. Setting up the project with Library. 
  3. Implementing the Download Listener with Kotlin. 
Step 1 - Creating a new project with Kotlin
  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.
Step 2 - Setting up the project with AndroidManifest
The following lines are added to your Kotlin project by default.
dependencies {   
    …  
   implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"  
   implementation 'com.android.support:appcompat-v7:26.1.0'  
   implementation 'com.android.support:support-annotations:26.1.0'  
   implementation 'com.android.support.constraint:constraint-layout:1.1.3'  
    …  
}
And also, we need to add the INTERNET/WRITE EXTERNAL STORAGE permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Step 3 - Implementation of Download Listener with Kotlin
  1. We need to add our WebView to our activity_main.xml file and initialize the WebView control. 
  2. Then, add the following lines.
    webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")  
    webview.webViewClient = MyClient()  
      
    webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
        val request = DownloadManager.Request(Uri.parse(url))  
        request.setMimeType(mimeType)  
        request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
        request.addRequestHeader("User-Agent", userAgent)  
        request.setDescription("Downloading file...")  
        request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
        request.allowScanningByMediaScanner()  
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
        request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
        val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
        dm.enqueue(request)  
        Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
    })
    Here, we have to add the download manager request with media scanner to notify that the file is downloading.
  3. Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED is used to notify a user when the download is completed.
Full Code of MainActivity
You can find the full code implementation of MainActivty.kt in the following code.
class MainActivity : AppCompatActivity() {  
  
    @SuppressLint("SetJavaScriptEnabled")  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
  
        webview.loadUrl("http://cbseacademic.in/SQP_CLASSXII_2016_17.html")  
        webview.webViewClient = MyClient()  
  
        webview.setDownloadListener({ url, userAgent, contentDisposition, mimeType, contentLength ->  
            val request = DownloadManager.Request(Uri.parse(url))  
            request.setMimeType(mimeType)  
            request.addRequestHeader("cookie", CookieManager.getInstance().getCookie(url))  
            request.addRequestHeader("User-Agent", userAgent)  
            request.setDescription("Downloading file...")  
            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimeType))  
            request.allowScanningByMediaScanner()  
            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)  
            request.setDestinationInExternalFilesDir(this@MainActivity, Environment.DIRECTORY_DOWNLOADS, ".png")  
            val dm = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager  
            dm.enqueue(request)  
            Toast.makeText(applicationContext, "Downloading File", Toast.LENGTH_LONG).show()  
        })  
  
    }  
  
    class MyClient : WebViewClient() {  
        override fun shouldOverrideUrlLoading(view: WebView, Url: String): Boolean {  
            view.loadUrl(Url)  
            return true  
  
        }  
    }  
  
    override fun onBackPressed() {  
        if (webview.canGoBack())  
            webview.goBack()  
        else  
            super.onBackPressed()  
  
    }  
}

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How to use KenburnsView in Kotlin

Introduction:

In this article, we will learn how use Kenburnsview in Android using Kotlin. Kenburnsview is an awesome Android library that provides an extension to ImageView that creates an immersive experience by animating its Drawable using the Ken Burns Effect.

Coding Part:

I have divided the coding part into 3 steps as shown in the following.

  1. Creating new project with Kotlin Support.

  2. Setting up the project with Kenburnsview Library.

  3. Implementing KenburnsView with Kotlin.

Step 1: Creating new project with Kotlin:

  1. Open Android Studio and Select Create new project.

  2. Name the project as your wish and tick the Kotlin checkbox support.

  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).

  4. Then Click “finish” button to create new project in Android Studio.

Step 2: Setting up the project with AndroidManifest:

We will add the following lines to your app level build.gradle to add KenburnsView library to your project.

dependencies { 
    …
    implementation 'com.flaviofaria:kenburnsview:1.0.7'
    …
}
repositories {
    mavenCentral()
}

Step 3: Implementation of KenburnsView with Kotlin

  1. We will start coding. Open your layout file. In my case, I have activity_main.xml included content_main.xml. So, I have opened content_main.xml.

  2. Then add the following lines.

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout 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"
              app:layout_behavior="@string/appbar_scrolling_view_behavior"
              tools:context="com.androidmads.kenburnsview.MainActivity"
              tools:showIn="@layout/activity_main">
    
        <com.flaviofaria.kenburnsview.KenBurnsView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/img"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/img1" />
    
    </android.support.constraint.ConstraintLayout>
  3. Then open your MainActivity.java file and Initialize the KenburnsView Library as shown in the following.

    var mImg: KenBurnsView? = null
    mImg = findViewById(R.id.img)
  4. We can pause, resume and stop the ken burns effect by the library itself using the following snippets respectively.

    mImg!!.pause()
    mImg!!.resume()
    mImg!!.stop()
  5. We can perform our defined operations based on the transitions of KenburnsView using the following snippets.

    mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
     override fun onTransitionStart(transition: Transition) {
    
     }
    
     override fun onTransitionEnd(transition: Transition) {
      if (imageId == R.drawable.img1) {
       imageId = R.drawable.img2
       mImg!!.setImageResource(R.drawable.img2)
      } else {
       imageId = R.drawable.img1
       mImg!!.setImageResource(R.drawable.img1)
      }
     }
    })
  6. Here, I have changed the image source to KenburnsView, when each image transitions end.

Full Code of MainActivity:

You can find the full code implementation of MainActivty.kt in the following

class MainActivity : AppCompatActivity() {

    private var mImg: KenBurnsView? = null
    private var fab: FloatingActionButton? = null
    private var isPlaying = true
    private var imageId: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imageId = R.drawable.img1

        fab = findViewById(R.id.fab)
        mImg = findViewById(R.id.img)

        fab!!.setOnClickListener {
            if (isPlaying) {
                mImg!!.pause()
                fab!!.setImageResource(R.drawable.ic_play)
            } else {
                mImg!!.resume()
                fab!!.setImageResource(R.drawable.ic_pause)
            }
            isPlaying = !isPlaying
        }

        mImg!!.setTransitionListener(object : KenBurnsView.TransitionListener {
            override fun onTransitionStart(transition: Transition) {

            }

            override fun onTransitionEnd(transition: Transition) {
                if (imageId == R.drawable.img1) {
                    imageId = R.drawable.img2
                    mImg!!.setImageResource(R.drawable.img2)
                } else {
                    imageId = R.drawable.img1
                    mImg!!.setImageResource(R.drawable.img1)
                }
            }
        })
    }
}

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How to do AsyncTask in Kotlin

kotlin_async
Introduction:
In this article, we will learn how perform AsyncTask in android with Kotlin. Async task is used to perform some asynchronous tasks without blocking the main thread. It is very useful in android development. Similar to java, the same code can be used in Kotlin with some minor modifications.
Coding Part:
I have divided the coding part into 3 steps as shown in the following.
  1. Creating new project with Kotlin Support.
  2. Setting up the project with AndroidManifest.
  3. Implementing Async tasks with Kotlin.
Without any delay, we will start coding for Kotlin AsyncTask.
Step 1: Creating new project with Kotlin:
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).
  4. Then Click “finish” button to create new project in Android Studio.
Step 2: Setting up the project with AndroidManifest:
Now, we will add the internet permission in Android Manifest file. Because we will see the example with URL Connection. Just open your AndroidManifest.xml file and add the following line.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Implementing Async tasks with Kotlin
We will start coding. Here, I have used the following simple API to retrieve android version details.
  1. I have included a Button and TextView in my layout (activity_main.xml) file. Here, Button and TextView is used to call the API and display the result from the API
    <?xml version="1.0" encoding="utf-8"?>  
    <android.support.constraint.ConstraintLayout 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"  
        tools:context=".MainActivity"  
        tools:layout_editor_absoluteX="0dp"  
        tools:layout_editor_absoluteY="81dp">  
      
        <TextView  
            android:id="@+id/my_text"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="72dp"  
            android:text="AsyncTask Example"  
            android:textSize="18sp"  
            android:textStyle="bold"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toTopOf="parent" />  
      
        <ProgressBar  
            android:id="@+id/MyprogressBar"  
            style="?android:attr/progressBarStyle"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="32dp"  
            android:visibility="invisible"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/my_text" />  
      
        <Button  
            android:id="@+id/CallBtn"  
            android:layout_width="wrap_content"  
            android:layout_height="wrap_content"  
            android:layout_marginEnd="8dp"  
            android:layout_marginStart="8dp"  
            android:layout_marginTop="36dp"  
            android:text="Execute AsyncTask"  
            app:layout_constraintEnd_toEndOf="parent"  
            app:layout_constraintStart_toStartOf="parent"  
            app:layout_constraintTop_toBottomOf="@+id/MyprogressBar" />  
      
    </android.support.constraint.ConstraintLayout>
Then open your Activity file (in my case MainActivity.kt) and create a class with AsynTask as a parent.
AsyncTask has three main methods.
  1. onPreExecute – State before task performance
  2. doInBackground – State for task performance
  3. onPostExecute – State after task performance
Add the following code with your AsyncTask class. Here I have used
HttpURLConnection” to access the API Link.
BufferedReader” to read the response output of the API Link.
JSONObject” to parse the response from server.
Async Task Class can be called in the following method.
AsyncTaskExample(this).execute()
Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following
class MainActivity : AppCompatActivity() {

    private val tag: String = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        CallBtn.setOnClickListener {
            AsyncTaskExample(this).execute()
        }
    }

    @SuppressLint("StaticFieldLeak")
    class AsyncTaskExample(private var activity: MainActivity?) : AsyncTask() {

        override fun onPreExecute() {
            super.onPreExecute()
            activity?.MyprogressBar?.visibility = View.VISIBLE
        }

        override fun doInBackground(vararg p0: String?): String {

            var result = ""
            try {
                val url = URL("http://demosmushtaq.16mb.com/api/post_sample.php?version_index=14")
                val httpURLConnection = url.openConnection() as HttpURLConnection

                httpURLConnection.readTimeout = 8000
                httpURLConnection.connectTimeout = 8000
                httpURLConnection.doOutput = true
                httpURLConnection.connect()

                val responseCode: Int = httpURLConnection.responseCode
                Log.d(activity?.tag, "responseCode - " + responseCode)

                if (responseCode == 200) {
                    val tempStream: InputStream = httpURLConnection.inputStream
                    result = convertToString(tempStream)
                }
            } catch (ex: Exception) {
                Log.d("", "Error in doInBackground " + ex.message)
            }
            return result
        }

        override fun onPostExecute(result: String?) {
            super.onPostExecute(result)
            activity?.MyprogressBar?.visibility = View.INVISIBLE
            if (result == "") {
                activity?.my_text?.text = activity?.getString(R.string.network_error)
            } else {
                var parsedResult = ""
                var jsonObject: JSONObject? = JSONObject(result)
                jsonObject = jsonObject?.getJSONObject("data")
                parsedResult += "Code Name : " + (jsonObject?.get("code_name")) + "\n"
                parsedResult += "Version Number : " + (jsonObject?.get("version_number")) + "\n"
                parsedResult += "API Level : " + (jsonObject?.get("api_level"))
                activity?.my_text?.text = parsedResult
            }
        }

        private fun convertToString(inStream: InputStream): String {

            var result = ""
            val isReader = InputStreamReader(inStream)
            val bReader = BufferedReader(isReader)
            var tempStr: String?

            try {

                while (true) {
                    tempStr = bReader.readLine()
                    if (tempStr == null) {
                        break
                    }
                    result += tempStr
                }
            } catch (Ex: Exception) {
                Log.e(activity?.tag, "Error in convertToString " + Ex.printStackTrace())
            }
            return result
        }
    }
}

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub.

How to custom fonts to Views - Android


In this article, we will learn how to apply custom fonts to Views in Android like Toolbar, MenuItem apart from the views like TextView, EditText.

FontUtils:

FontUtils is a tiny font utility library used to apply custom fonts to Views. It supports the following views.
  • Toolbar
  • NavigationView
  • Menu
  • Submenu
  • Other Views like EditText, TextView, etc.
This library is support the following Languages.
  • Android – Java
  • Android – Kotlin
  • Android

Coding Part:

Steps:

I have split this part into 3 steps as in the following.
Step 1: Creating New Project with Empty Activity.
Step 2: Setting up the Library for Android Views.
Step 3: Applying Custom fonts to Android Views.

Step 1:Creating New Project with Empty Activity

  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and select Empty activity.
  3. Click “finish” button to create new project in Android Studio.

Step 2:Setting up the Library for Android Views

In this part, we will see how to setup the library for the project.
  1. Open your app level build.gradle file and add the following lines to download the library.
    …
    implementation 'com.ajts.androidmads.fontutils:fontutils:1.0.1'
    …
    
  2. Then Click “Sync Now” to download the library.
  3. We need to use “compile” instead of “implementation” if we have using Android Studio Version below 3.0.

Step 3:Applying Custom fonts to Android Views

In this part, we will see how to apply custom fonts to Views. Here, we have to use “Typeface” and to more about “TypeFace” Click here.
  1. In this article, I am assigning the fonts from Assets folder. To create assets folder, right on the app folder and select New. Then select Folder and click assets folder.
  2. Then Copy and Paste the fonts you want to use with your application.
  3. The following line shows how to initialize the library.
    // Applying Custom Font
    Typeface typeface = Typeface.createFromAsset(getAssets(), "custom_font.ttf");
    // Init Library
    FontUtils fontUtils = new FontUtils();
  4. Then Initialize your Views and apply the fonts to the Views. The following example shows how to apply the fonts to Toolbar of your application.
    // Apply font to Toolbar
    fontUtils.applyFontToToolbar(toolbar, typeface);
  5. You can apply custom fonts to other views like NavigationView, Menu, Submenu, TextView like in following example.
    // Apply font to NavigationView
    fontUtils.applyFontToNavigationView(navigationView, typeface);
    // Apply font to Menu
    fontUtils.applyFontToMenu(menu, typeface);
    // Apply font to Other Views like TextView...
    fontUtils.applyFontToView(textview, typeface);
    fontUtils.applyFontToView(editText, typeface);
    fontUtils.applyFontToView(radioButton, typeface);
    fontUtils.applyFontToView(checkBox, typeface);

For Kotlin

We need to do the same steps mentioned. But we need to include Kotlin support while creating the project. Apply font to Views in Kotlin as show below.
// Applying Custom Font
val typeface = Typeface.createFromAsset(assets, "custom_font.ttf")
// Init Library
val fontUtils = FontUtils()
// Apply font to Toolbar
fontUtils.applyFontToToolbar(toolbar, typeface)
// Apply font to NavigationView
fontUtils.applyFontToNavigationView(navigationView, typeface)
// Apply font to Menu
fontUtils.applyFontToMenu(menu, typeface)
// Apply font to Other Views like TextView...
fontUtils.applyFontToView(textview, typeface)
fontUtils.applyFontToView(editText, typeface)
fontUtils.applyFontToView(radioButton, typeface)
fontUtils.applyFontToView(checkBox, typeface)

For Xamarin.Android

We can apply the same with Xamarin.Android. To know more Click Here.


Download Code

The article is informative do like and star the repo in GitHub. You can download the code here.
Note:
Java and Kotlin Android Support
https://github.com/androidmads/FontUtils
Xamarin.Android Support
https://github.com/Xamarin-Gists/XAFontUtilsLibrary

Alert Builder in Android -Kotlin

In this article, we will learn how to work with Alerts in Android using Kotlin. if you are new to Kotlin read my previous articles. This article is very basic. But very worthier for learning from Scratch.
Implementing Alerts in Android using Kotlin is similar to Java implementation and so, it is very easy to understand. Here, we will learn the following alerts.
  1. Alert with two options.
  2. Alert with list.

Coding Part

I have split this article into 3 steps as follows:

Creating new Android Project with Kotlin in Android Studio 

By default, Android Studio 3.0 has the checkbox for Kotlin Support for your Android Application. Create new project in Android studio, check the Kotlin support, and start as usual with Android Studio 3.0.


For migrating Java Android Project to Kotlin Android Project, you can do the following processes.

Configuring Kotlin
Kotlin support can be configured by selecting Tools  Kotlin  Configure Kotlin. Then, Click “Sync Now”. This step is applicable to the Android Studio pre versions of 3.0. Best way is you must update your Android Studio.

In Android Studio 3.0, by default you have Kotlin Activity. For Android Studio with Version less than 3.0, can convert their Java activity into Kotlin Activity.

Open Quick Search or Click Ctrl + Shift + A for Windows Users and Search and Select “Convert Java to Kotlin” or simply Select Ctrl + Shift + Alt + K.

Adding User Interface in your Layout file 

In this step, we will add buttons for triggering normal alerts and list alerts. Open your activity_main.xml file and paste the following.
<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout 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"  
    tools:context="com.ajts.androidmads.kotlinalerts.MainActivity"  
    tools:layout_editor_absoluteY="81dp">  
  
    <Button  
        android:id="@+id/optionAlert"  
        android:layout_width="0dp"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="184dp"  
        android:text="Normal Alert"  
        app:layout_constraintEnd_toEndOf="@+id/listAlert"  
        app:layout_constraintStart_toStartOf="@+id/listAlert"  
        app:layout_constraintTop_toTopOf="parent"  
        android:onClick="showNormalAlert"/>  
  
    <Button  
        android:id="@+id/listAlert"  
        android:layout_width="123dp"  
        android:layout_height="wrap_content"  
        android:layout_marginTop="7dp"  
        android:text="List Alert"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toBottomOf="@+id/optionAlert"  
        android:onClick="showListAlert" />  
  
</android.support.constraint.ConstraintLayout>  
The Screen looks like the below screenshot.


Implementing the alerts in Kotlin 

Now open your Activity file and in my case, I am opening “MainActivity.kt”.
Show Alert Dialog with two options
fun showNormalAlert(v: View){  
    val dialog = AlertDialog.Builder(this).setTitle("Kotlin Study").setMessage("Alert Dialog")  
            .setPositiveButton("Confirm", { dialog, i ->  
                Toast.makeText(applicationContext, "Hello Friends", Toast.LENGTH_LONG).show()  
            })  
            .setNegativeButton("Cancel", { dialog, i -> })  
    dialog.show()  
} 
Showing List Type Alert Dialog
fun showListAlert(v: View){  
    val items = arrayOf("Android", "iOS", "Windows")  
    val dialog = AlertDialog.Builder(this).setTitle("Select your Mobile OS").setItems(items,  
            {  
                dialog, which ->  
                Toast.makeText(applicationContext, items[which], Toast.LENGTH_LONG).show();  
            })  
    dialog.show()  
}

Full Code

You can find the full code implementation below.
package com.ajts.androidmads.kotlinalerts  
  
import android.support.v7.app.AppCompatActivity  
import android.os.Bundle  
import android.support.v7.app.AlertDialog  
import android.view.View  
import android.widget.Toast  
  
class MainActivity : AppCompatActivity() {  
  
    override fun onCreate(savedInstanceState: Bundle?) {  
        super.onCreate(savedInstanceState)  
        setContentView(R.layout.activity_main)  
    }  
  
    fun showNormalAlert(v: View){  
        val dialog = AlertDialog.Builder(this).setTitle("Kotlin Study").setMessage("Alert Dialog")  
                .setPositiveButton("Confirm", { dialog, i ->  
                    Toast.makeText(this@MainActivity, "Hello Friends", Toast.LENGTH_LONG).show()  
                })  
                .setNegativeButton("Cancel", { dialog, i -> })  
        dialog.show()  
    }  
  
    fun showListAlert(v: View){  
        val items = arrayOf("Android", "iOS", "Windows")  
        val dialog = AlertDialog.Builder(this).setTitle("Select your Mobile OS").setItems(items,  
                {  
                    dialog, which ->  
                    Toast.makeText(applicationContext, items[which], Toast.LENGTH_LONG).show();  
                })  
        dialog.show()  
    }  
}
If this article is useful to you, do like it and keep on commenting if you have any clarifications.

Download Code: 

You can download sample code from the following GitHub link.

Kotlin HTTP Example (Using Fuel Http)

kotlin

Introduction:

After the announcement of Google on Google I/O 2017, we have seen the series of tutorials in Kotlin. If you are new to Kotlin you can learn Kotlin from our previous articles. We had been crossed Basics of Kotlin and Hello World function, How to use ListView, RecyclerView in Kotlin and How to implement SQLite storage in Kotlin with CRUD operations.

In this article, we will learn how to make server call (i.e. HTTP Connection) from Kotlin powered application to web services.

Coding Part:
I have divided the coding part into 3 steps as shown in the following.
  1. Creating new project.
  2. Setting up the project with Fuel HTTP.
  3. Implementing the Fuel HTTP Service Call.
Let’s start coding for Fuel HTTP.
Step 1: Creating new project:
  1. Open Android Studio and Select Create new project.
  2. Name the project as your wish and tick the Kotlin checkbox support.
  3. Then Select your Activity type (For Example: Navigation Drawer Activity, Empty Activity, etc.).
  4. Then Click “finish” button to create new project in Android Studio
Step 2: Setting up the project:
Now, we will setting up the project for Fuel HTTP.
1.      Open your app level build.gradle file and add the following line.
implementation 'com.github.kittinunf.fuel:fuel-android:1.6.0'
2.      If you are using Android Studio Version below 3.0, the add the following (Optional Step)
compile 'com.github.kittinunf.fuel:fuel-android:1.6.0'
3.       Then Click “Sync Now” to download the library and add to the project.
After this, you are ready to implement HTTP Service Call from your Application.
Step 3: Fuel HTTP implementation:
Now, we will setting up the project for Fuel HTTP.
1.      Open your AndroidManifest.xml and Add permission to access internet.
<uses-permission android:name="android.permission.INTERNET"/>
2.   Open your activity_main.xml file and create the User Interface as you wanted or Paste the following code.
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.androidmads.kotlinfuelhttpsample.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="GET Request's Response"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvGetResponse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#e1e1e1"
            android:padding="10dp"
            android:text="" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@color/colorPrimary"
            android:onClick="httpGetJson"
            android:text="GET RESPONSE"
            android:textColor="#ffffff" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="POST Request's Response"
            android:textColor="#000000" />

        <TextView
            android:id="@+id/tvPostResponse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:background="#e1e1e1"
            android:padding="10dp"
            android:text="" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:background="@color/colorPrimary"
            android:onClick="httpPostJson"
            android:text="POST RESPONSE"
            android:textColor="#ffffff" />

    </LinearLayout>
</ScrollView>
Layout Preview
1.       Then Open your Activity file and here I am opening MainActivity.java file.
2.      Initialize the fuel library by the following code
FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";
Here, you must specify the base address of your service. It will start or initialize the library.
GET REQUEST
We will use “Fuel.get()” to make server call with Get method. The following code shows how to implement this.
Fuel.get("<Service Link without base path>")
.responseJson { request, response, result ->
 Log.v(“response”, result.get().content)
}
POST REQUEST
We will use “Fuel.post()” to make server call with Post method. The following code shows how to implement this.
Fuel.post("<Service Link without base path>", listOf("<key>" to "<value>"))
.responseJson { request, response, result ->
 Log.v(“response”, result.get().content)
}
You can get the response as string or json by specify the response type “responseString” or “responseJson” respectively.You can pass the data to service using “listOf” method. It is an optional value. You can also access the without the parameters to be passed
You can get response from the result using “result.get().content” as mentioned in the code above.

Full Code of MainActivity:
You can find the full code implementation of MainActivty.kt in the following.
class MainActivity : AppCompatActivity() {

    var tvGetResponse: TextView? = null
    var tvPostResponse: TextView? = null
    var progress: ProgressDialog? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initViewsAndWidgets()
        FuelManager.instance.basePath = "http://demosmushtaq.16mb.com";
    }

    private fun initViewsAndWidgets() {
        tvGetResponse = findViewById(R.id.tvGetResponse)
        tvPostResponse = findViewById(R.id.tvPostResponse)
        progress = ProgressDialog(this)
        progress!!.setTitle("Kotlin Fuel Http Sample")
        progress!!.setMessage("Loading...")
    }

    fun httpGetJson(view: View) {
        try {
            progress!!.show()
            Fuel.get("api/get_sample.php").responseJson { request, response, result ->
                tvGetResponse!!.text = result.get().content
            }
        } catch (e: Exception) {
            tvGetResponse!!.text = e.message
        } finally {
            progress!!.dismiss()
        }
    }

    fun httpPostJson(view: View) {
        try {
            progress!!.show()
            Fuel.post("api/post_sample.php", listOf("version_index" to "1")).responseJson { request, response, result ->
                tvPostResponse!!.text = result.get().content
            }
        } catch (e: Exception) {
            tvPostResponse!!.text = e.message
        } finally {
            progress!!.dismiss()
        }
    }
}

Download Code: 

You can download sample code from the following GitHub link.