Camera Intent with Kotlin-Android

We know that in many situations our app needs to use the Camera of the device to take pictures, You might know how to use Camera feature in your Android app with Java which is a traditional language for Android .

Here we are going to learn how to use Camera feature in our App with Kotlin.

Add permissions

Make sure that you have added the following permissions into your manifest.xml file.

<uses-permission android:name=”android.permission.CAMERA”/>
<uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”/>
<uses-permission android:name=”android.permission.READ_EXTERNAL_STORAGE”/>

Set up Layout

We are going to setup Layout file for MainActivity Our layout consists of an ImageView and a Capture Button as given below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <LinearLayout
       android:layout_centerInParent="true"
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

       <ImageView
           android:id="@+id/image_view"
           android:background="@drawable/img_placehlder"
           android:layout_gravity="center_horizontal"
           android:layout_width="200dp"
           android:layout_height="300dp" />
       <Button
           android:id="@+id/btn_capture"
           android:text="Capture"
           android:layout_marginTop="12dp"
           android:layout_gravity="center_horizontal"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content" />

   </LinearLayout>

</RelativeLayout>

The layout will be like this.

Set Up MainActivity

Now we are going to set up our MainActivity.kt, Have the following methods.

Firstly we need to handle the permissions, From Android 6.0 (Marshmellow) Google introduced Run time permissions. We need to declare the permissions in the manifest.xml file and then request these permissions in runtime so that user can approve or decline each permission.  Add the following code to check permissions and request permission

    
    private fun checkPersmission(): Boolean {
        return (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
    }

    private fun requestPermission() {
        ActivityCompat.requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE, CAMERA),
        PERMISSION_REQUEST_CODE)
    }
    

We are going to check this permission in Capture Button click. So if the user is already given the permissions to access Camera and External Storage we can directly open the Camera to take Picture. But we should manage the onRequestPermissionsresult() to open the camera after the request for permissions and if the user accepted it. This includes a method takePicture() which is defined later. The code is given below

   
   override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {

                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                        &&grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                    takePicture()

                } else {
                  Toast.makeText(this,"Permission Denied",Toast.LENGTH_SHORT).show()
                }
                return
            }

            else -> {

            }
        }
    }
    

Now let’s take a look at takePicture() method. In this method, we set up an Intent to open the Camera. This method consists of a method called createFile() used to create a File to store the Image.

@Throws(IOException::class)
    private fun createFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
                "JPEG_${timeStamp}_", /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = absolutePath
        }
    }

We need to Configure the FileProvider in our app’s manifest.xml file to add a provider to our application.

<application>
   ... 
<provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.android.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_path">
                
            </meta-data>
        </provider>
    ...
</application>

Create a new file file_path.xml under  res/xml folder.  Make sure you have added your package name in the path instead of “com.kotlincodes.cameraintentwithkotlin_android”

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images"
        path="Android/data/com.kotlincodes.cameraintentwithkotlin_android/files/Pictures" />
</paths>

Now we can set an Intent to start Camera to capture an Image as follows

 
 private fun takePicture() {

        val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val file: File = createFile()

        val uri: Uri = FileProvider.getUriForFile(
                this,
                "com.example.android.fileprovider",
                file
        )
        intent.putExtra(MediaStore.EXTRA_OUTPUT,uri)
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)

    }
    

This method will open the Camera and we can capture an Image. After taking a Picture we need to show this Image on our ImageView. To set the ImageView add the following code

 
 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {

            //To get the File for further usage
            val auxFile = File(mCurrentPhotoPath)


           var bitmap :Bitmap=BitmapFactory.decodeFile(mCurrentPhotoPath)
            imageView.setImageBitmap(bitmap)

        }
    }

Now we are all set to run the project. Please find the Complete code for MainActivity.kt file below.

MainActivity.kt

package com.kotlincodes.cameraintentwithkotlin_android

import android.Manifest.permission.CAMERA
import android.Manifest.permission.READ_EXTERNAL_STORAGE
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v4.content.FileProvider
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


class MainActivity : AppCompatActivity() {
    lateinit var imageView: ImageView
    lateinit var captureButton: Button

    val REQUEST_IMAGE_CAPTURE = 1


    private val PERMISSION_REQUEST_CODE: Int = 101

    private var mCurrentPhotoPath: String? = null;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        imageView = findViewById(R.id.image_view)
        captureButton = findViewById(R.id.btn_capture)
        captureButton.setOnClickListener(View.OnClickListener {
            if (checkPersmission()) takePicture() else requestPermission()
        })


    }


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_REQUEST_CODE -> {

                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {

                    takePicture()

                } else {
                    Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show()
                }
                return
            }

            else -> {

            }
        }
    }

    private fun takePicture() {

        val intent: Intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
        val file: File = createFile()

        val uri: Uri = FileProvider.getUriForFile(
                this,
                "com.example.android.fileprovider",
                file
        )
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri)
        startActivityForResult(intent, REQUEST_IMAGE_CAPTURE)

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK) {

            //To get the File for further usage
            val auxFile = File(mCurrentPhotoPath)


            var bitmap: Bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath)
            imageView.setImageBitmap(bitmap)

        }
    }

    private fun checkPersmission(): Boolean {
        return (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) ==
                PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
    }

    private fun requestPermission() {
        ActivityCompat.requestPermissions(this, arrayOf(READ_EXTERNAL_STORAGE, CAMERA), PERMISSION_REQUEST_CODE)
    }

    @Throws(IOException::class)
    private fun createFile(): File {
        // Create an image file name
        val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
        val storageDir: File = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
        return File.createTempFile(
                "JPEG_${timeStamp}_", /* prefix */
                ".jpg", /* suffix */
                storageDir /* directory */
        ).apply {
            // Save a file: path for use with ACTION_VIEW intents
            mCurrentPhotoPath = absolutePath
        }
    }
}

That’s it! Now run the project!

The full source code is available here.

Thanks for reading!


RecyclerView With Kotlin – Android

We know that if we need to display a scrolling list of elements based on a large set of data sets which may frequently change we should use RecyclerView.

RecyclerView is a much-advanced version of ListView with a lot of improvements made. You might have Implemented RecyclerView in android with Java but here we are going to learn how to implement a RecyclerView with Kotlin.

Lets go for a detailed tutorial for implementation of RecyclerView with Kotlin Android.

Import the following dependency to the app level build.gradle to add the RecyclerView In your project.


implementation ‘com.android.support:recyclerview-v7:27.1.1’

N we are going to set up the MainActivity layout file activity_main.xml. The Layout consists of a RecyclerView as given below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".activity.MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

   </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

Now we are going to set up a list_item_view for RecyclerView which includes only one TextView. The layout file is given below.

list_item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/title"
        android:textSize="18sp"
        android:padding="6dp"
        android:maxLines="1"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <View
        android:background="#000"
        android:layout_width="match_parent"
        android:layout_height="1dp"/>

</LinearLayout>

To populate our data with RecyclerView, We need a RecyclerViewAdapter class RecyclerViewAdapter.kt. Which is given below. This class inherited from RecyclerView.Adapter() . It has three abstract methods.

  • getItemCount(): Returns the total number of items in the data set held by the adapter. In our project, we return the size of our dataList Array.
  • onCreateViewHolder(parent : ViewGroup, viewType:int) ; Viewholder :
    This method onCreateViewHolder(ViewGroup, int) create a RecyclerView.ViewHolder initializes some private fields to be used by RecyclerView.
  • onBindViewHolder(holder:,position :int) :
    This method internally onBindViewHolder(ViewHolder, int) update RecyclerView.ViewHolder with the item at the given position and also sets up some private fields to be used by RecyclerView.  in this method we can set up our TextView or any other  Views with our data.

Our RecyclerViewAdapter.kt is shown below.

RecyclerViewAdapter.kt

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.TextureView
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.shrishtionline.recyclerviewwithkotlin.R

class RecyclerViewAdapter(private var context: Context,private var dataList:ArrayList<String>):RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {
    override fun getItemCount(): Int {
        return dataList.size;
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item_view, parent, false))
    }

    override fun onBindViewHolder(holder:ViewHolder, position: Int) {
        holder.textView.text=dataList.get(position);
    }


    class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
        var textView:TextView =itemView!!.findViewById(R.id.text_view)
    }
}

Now we need to set up our MainActivity.kt class.

  • The class includes a function addAnimals() to add some data to our list.

MainActivity.kt

package com.shrishtionline.recyclerviewwithkotlin

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView

class MainActivity : AppCompatActivity() {

    lateinit var recyclerView: RecyclerView
    lateinit var adapter: RecyclerViewAdapter
    var dataList:ArrayList<String> = ArrayList();

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

        //Initializing RecyclerView
        recyclerView=findViewById(R.id.recycler_view)


        adapter= RecyclerViewAdapter(this,dataList)

        //Set up recyclerview with Vertical LayoutManager and the adapter

        recyclerView.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)

        //Adding animal names
        addAnimals();

        // Notify the adapter for data change.
        adapter.notifyDataSetChanged()

    }

    private fun addAnimals() {
        dataList!!.add("Dog")
        dataList!!.add("Cat")
        dataList!!.add("Monkey")
        dataList!!.add("lion")
        dataList!!.add("Elephent")
        dataList!!.add("Cheetah")
        dataList!!.add("Snake")
        dataList!!.add("Cow")
        dataList!!.add("Ant")
        dataList!!.add("Tiger")
        dataList!!.add("Lizard")

    }
}

That’s it! Now run the project!

The full source code is available here.

Thanks for reading!


Retrofit with Kotlin-Android

In this tutorial we will learn how to implement Retrofit HTTP client in Android with Kotlin.

Retrofit is a powerful HTTP client for an Android and Java built by awesome folks at Square . Retrofit Configured with convertors makes it easy to serialize structured data sets. Typically for JSON  we uses Gson convertors to serialization and De-serialization process.

Retrofit uses the Okhttp library for for HTTP requests.

Please find the sample project given below.

  • Open your project and add dependencies into app level  build.gradle ( Module:app) file.  Here we adds Gson,RecyclerView,CardView,Piccasso and Retrofit libraries
dependencies {
    ...

    implementation 'com.google.code.gson:gson:2.8.4'
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
    implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
    implementation "com.android.support:cardview-v7:27.1.1"
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.squareup.picasso:picasso:2.71828'

    ...
}
  • Make sure you have added the INTERNET permission in AndroidManifest.xml file like this.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="kotlincodes.com.retrofitwithkotlin">
    <uses-permission android:name="android.permission.INTERNET"/>

    <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=".activity.MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>
  • Next we need to create data model to parse our sample Json response . The sample response is given below.
Sample response

  • Now Create a Kotlin Class named DataModel.kt under model package like shown below.

DataModel.kt 

package kotlincodes.com.retrofitwithkotlin.model

import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName


data class DataModel(

        @Expose
        @SerializedName("albumId")
        val albumid: Integer,
        @Expose
        @SerializedName("id")
        val id: Integer,
        @Expose
        @SerializedName("title")
        val title: String,
        @Expose
        @SerializedName("url")
        val url: String,
        @Expose
        @SerializedName("thumbnailUrl")
        val thumbnailurl: String
)
  • Now create a retrofit instance to make a network request to a REST API with Retrofit.
  • Here we creates a Kotlin object ApiClient.kt under retrofit package.
  • The BASE_URL is the basic URL of your API where we will make a call

ApiClient.kt

import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object ApiClient {

    var BASE_URL:String="https://jsonplaceholder.typicode.com/"
    val getClient: ApiInterface
        get() {

            val gson = GsonBuilder()
                    .setLenient()
                    .create()
            val interceptor = HttpLoggingInterceptor()
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
            val client = OkHttpClient.Builder().addInterceptor(interceptor).build()

            val retrofit = Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(client)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .build()

            return retrofit.create(ApiInterface::class.java)

        }

}
  • Define End Points : Now we create an interface ApiInterface.kt under retrofit package to define the api end points

ApiInterface.kt

import kotlincodes.com.retrofitwithkotlin.model.DataModel
import retrofit2.Call
import retrofit2.http.GET

interface ApiInterface {

    @GET("photos")
    fun getPhotos(): Call<List<DataModel>>

}
  • Set up MainActivity Class
  • Now we are all set to make an api call in MainActivity.kt .
  • getData() method is used to make HTTP request using Retrofit
  • Here we fetch data and populate it in to a RecyclerView ,  the RecyclerViewAdapter DataAdapter and RecyclerView layouts are described later.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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=".activity.MainActivity">

   <android.support.v7.widget.RecyclerView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="wrap_content">

   </android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

MainActivity.kt 

class MainActivity : AppCompatActivity() {

    lateinit var progerssProgressDialog: ProgressDialog
    var dataList = ArrayList<DataModel>()
    lateinit var recyclerView: RecyclerView
    lateinit var adapter:DataAdpter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        recyclerView = findViewById(R.id.recycler_view)

        //setting up the adapter
        recyclerView.adapter= DataAdpter(dataList,this)
        recyclerView.layoutManager=LinearLayoutManager(this,LinearLayoutManager.VERTICAL,false)

        progerssProgressDialog=ProgressDialog(this)
        progerssProgressDialog.setTitle("Loading")
        progerssProgressDialog.setCancelable(false)
        progerssProgressDialog.show()
        getData()

    }

    private fun getData() {
        val call: Call<List<DataModel>> = ApiClient.getClient.getPhotos()
        call.enqueue(object : Callback<List<DataModel>> {

            override fun onResponse(call: Call<List<DataModel>>?, response: Response<List<DataModel>>?) {
                progerssProgressDialog.dismiss()
                dataList.addAll(response!!.body()!!)
                recyclerView.adapter.notifyDataSetChanged()
            }

            override fun onFailure(call: Call<List<DataModel>>?, t: Throwable?) {
                progerssProgressDialog.dismiss()
            }

        })
    }


}
  • Set up RecyclerView 
  • To set up RecyclerView we need a list layout and RecyclerView.Adapter DataAdapter.kt as given below.
  • The layout includes only a text view to show the title.

list_item_home.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_margin="6dp"
    app:contentPadding="12dp"
    android:layout_height="wrap_content">

    <TextView
        android:maxLines="1"
        android:id="@+id/title"
        android:layout_gravity="center"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.v7.widget.CardView>

DataAdapter.kt

package kotlincodes.com.retrofitwithkotlin.adapters

import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import kotlincodes.com.retrofitwithkotlin.R
import kotlincodes.com.retrofitwithkotlin.model.DataModel

class DataAdpter(private var dataList: List<DataModel>, private val context: Context) : RecyclerView.Adapter<DataAdpter.ViewHolder>() {


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(LayoutInflater.from(context).inflate(R.layout.list_item_home, parent, false))
    }

    override fun getItemCount(): Int {
       return dataList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val dataModel=dataList.get(position)

        holder.titleTextView.text=dataModel.title
    }


    class ViewHolder(itemLayoutView: View) : RecyclerView.ViewHolder(itemLayoutView) {
        lateinit var titleTextView:TextView
        init {
            titleTextView=itemLayoutView.findViewById(R.id.title)

        }

    }

}

Now we are all done. We have how to implement Retrofit with Kotlin and Implantation of   You can also find the Source the project from 


ViewPager In Kotlin Android

Here we provides a simple tutorials to implement ViewPager in Kotlin.

ViewPager is one of most popular widgets available in android libraries. It is used in most of the famous apps like PlayStore,WhatsApp etc.

ViewPager is a widget that is used to implement tabs in Android Applications. ViewPager allows users to swipe left or right to see new screens.

Setup Layout file

This step is to add ViewPager in your Layout file. Go to your xml file and add the following code into it.

Make sure you have added the following dependency in your build.gradle file

implementation ‘com.android.support:design:27.1.1’

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical">

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:tabGravity="fill"
        app:tabMode="fixed" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#c6c4c4" />

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>

Implementing The Activity

Now we will implement the MainActivity.kt. Please keep in mind.

  • MainActivity class have a Fragment and FragmentPagerAdapter to setup the view pager, this are defined bit later
  • FragmentPagerAdapter inherited from PagerAdapter
  • Function initViews()  initializes the views
  • Function setupViewPager()  setting up the ViewPager 

MainActivity.ktI

package kotlincodes.com.viewpagerkotlin.activity

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.design.widget.TabLayout
import android.support.v4.view.ViewPager
import kotlincodes.com.viewpagerkotlin.R
import kotlincodes.com.viewpagerkotlin.ViewPagerAdapter.MyFragmentPagerAdapter
import kotlincodes.com.viewpagerkotlin.fragments.MyFrament

class MainActivity : AppCompatActivity() {

    private lateinit var viewpager: ViewPager
    private lateinit var tabs: TabLayout

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

        initViews()

        setupViewPager()
    }

    private fun initViews() {
        tabs = findViewById(R.id.tabs)
        viewpager = findViewById(R.id.viewpager)
    }

    private fun setupViewPager() {

        val adapter = MyFragmentPagerAdapter(getSupportFragmentManager())

        var firstFragmet: MyFrament = MyFrament.newInstance("First Fragment")
        var secondFragmet: MyFrament = MyFrament.newInstance("Second Fragment")
        var thirdFragmet: MyFrament = MyFrament.newInstance("Third Fragment")

        adapter.addFragment(firstFragmet, "ONE")
        adapter.addFragment(secondFragmet, "TWO")
        adapter.addFragment(thirdFragmet, "THREE")

        viewpager!!.adapter = adapter

        tabs!!.setupWithViewPager(viewpager)

    }
}

Implementing The PagerAdapter Class

Now that we have the MainActivity.kt covered, we need to define the FragmentPagerAdapter Class. We have a addFragment inside FragmentPagerAdapter to add the Fragments .

MyFragmentPagerAdapter.kt

package kotlincodes.com.viewpagerkotlin.ViewPagerAdapter

import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import java.nio.file.Files.size
import android.support.v4.app.FragmentPagerAdapter
import kotlincodes.com.viewpagerkotlin.fragments.MyFrament


class MyFragmentPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
    private val mFragmentList: ArrayList<Fragment> = ArrayList()
    private val mFragmentTitleList: ArrayList<String> = ArrayList()

    override fun getItem(position: Int): Fragment {
        return mFragmentList.get(position)
    }

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

    fun addFragment(fragment: Fragment, title: String) {
        mFragmentList.add(fragment)
        mFragmentTitleList.add(title)
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return mFragmentTitleList.get(position)
    }
}

Setting Up The Fragment

We are almost finished now we need to setup the Fragmet class. First we need to set the fragment_home.xml layout

Layout have only a TextView to indicate the changes .

fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:padding="12dp"
        android:background="#000"
        android:id="@+id/text"
        android:layout_centerInParent="true"
        android:textSize="22dp"
        android:textAllCaps="true"
        android:text="Fragment ONE"
        android:textAlignment="center"
        android:textColor="#fff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</RelativeLayout>

now we need to setup the Fragment class MyFragment.kt

package kotlincodes.com.viewpagerkotlin.fragments

import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.support.v4.view.ViewPager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.TextureView
import android.widget.TextView
import kotlincodes.com.viewpagerkotlin.R
import android.provider.AlarmClock.EXTRA_MESSAGE
import android.provider.AlarmClock.EXTRA_MESSAGE


class MyFrament : Fragment() {
    companion object {
        fun newInstance(message: String): MyFrament {

            val f = MyFrament()

            val bdl = Bundle(1)

            bdl.putString(EXTRA_MESSAGE, message)

            f.setArguments(bdl)

            return f

        }
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        var view: View? = inflater.inflate(R.layout.fragment_home, container, false);

        val message = arguments!!.getString(EXTRA_MESSAGE)

        var textView: TextView = view!!.findViewById(R.id.text)
        textView!!.text = message

        return view
    }


}

That’s With the above we can simply implement a  ViewPager in Kotlin. you can also get a Source code of the project from GitHub


Country Code Picker with Kotlin

Country code pickers are used to search and select country code or international phone code in android. This example describes how to add a country code picker using Kotlin for Android application .

  • First we needed to add the following dependency into our applications app level build.gradle file.

implementation ‘com.hbb20:ccp:2.2.2’

  • Add the following code into your activity_main.xml file 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <com.hbb20.CountryCodePicker
        app:ccp_hintExampleNumber="true"
        android:id="@+id/country_code_picker"
        android:clickable="true"
        android:focusable="true"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

    </com.hbb20.CountryCodePicker>

</RelativeLayout>

To hide flag
app:ccp_showFlag=”false”

To hide Name code
app:ccp_showNameCode=”false”

  • In your MainActivity.kt
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.hbb20.CCPCountry
import com.hbb20.CountryCodePicker

class MainActivity : AppCompatActivity() ,CountryCodePicker.OnCountryChangeListener{
    private var ccp:CountryCodePicker?=null
    private var countryCode:String?=null
    private var countryName:String?=null

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

         ccp = findViewById(R.id.country_code_picker)
        ccp!!.setOnCountryChangeListener(this)

        //to set default country code as Japan
        
        ccp!!.setDefaultCountryUsingNameCode("JP")
    }

    override fun onCountrySelected() {
        countryCode=ccp!!.selectedCountryCode
        countryName=ccp!!.selectedCountryName

        Toast.makeText(this,"Country Code "+countryCode,Toast.LENGTH_SHORT).show()
        Toast.makeText(this,"Country Name "+countryName,Toast.LENGTH_SHORT).show()
    }

}

That’s it! Now run the project!

Thanks for reading!


Get Started with Kotlin in Android studio

Kotlin is fully supported with android studio v3.0 and Higher.

  • Setup Kotlin to Android Studio

Important : The android studio version must be 3.0 or higher

To add Kotlin support to the android studio we need to install the Kotlin plugin for your Android Studio.

To add the Kotlin plugin open

Android Studio File → Settings  → Plugins →type “Kotlin” in search box → Click Browse in Repositories → install →  Restart Android studio to activate the Plugin

 

Add Kotlin to the existing project

Add classpath in project level build.gradle.

Also here defined a variable kotlin_version as ext.kotlin_version = ‘1.2.41’ to share the version to all.

<// Top-level build file where you can add configuration options common to all sub-projects/modules.

    buildscript {
        ext.kotlin_version = '1.2.41'
        repositories {
            google()
            jcenter()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:3.0.1'
            classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

            // NOTE: Do not place your application dependencies here; they belong
            // in the individual module build.gradle files
        }
    }

    allprojects {
        repositories {
            google()
            jcenter()
        }
    }

    task clean(type: Delete) {
        delete rootProject.buildDir
    }

2. Add dependencies to app level build.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

dependencies {

implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

} 

 

Create a new project with Kotlin

Open android studio then click File –> New project you will get a window like below

Mark Include Kotlin Support 

Press Next–>Opens a page to select minimum SDK version — select API v15

Press Next –>Opens a page to select the default activity type — Choose Empty Activity from the list

Press Next –> Opens a page to change the default activity name

Press Finish — >Opens A new Android Project with Kotlin Support.


Kotlin : A new era in android app development

  • Introduction

Since long we have known and uses Java as the primary language for android app development. But recently a comparatively new language called Kotlin is taking over java in android development , A lot of developers now chooses Kotlin in their new android projects instead of Java.

  • What is Kotlin

Kotlin is a general purpose, open source, statically typed programming language for modern multi-platform applications. Kotlin combines object-oriented and functional programming features.  It is mainly focused on interoperability, safety, clarity, and tooling support.

Kotlin is developed by JetBrains,the company behind IntelliJ IDEA ,in 2010 and has been open source since 2012.

  • History

In July 2011, JetBrains unveiled Project Kotlin, a new language for the JVM, which had been under development for a year. Development lead by Andrey Breslav stated that Kotlin is   “better language” than Java, but still be fully interoperable with Java code, allowing companies to make a gradual migration from Java to Kotlin.One of the main goals was to compile as quickly as java

In February 2012 JetBrains open sourced the project under the Apache 2 licence.

Officially stable release Kotlin v1.0 was released on February 15 ,2016.

In 2017 annual developer conference held by google ( Google I/O  ) announced first-class support for Kotlin on Android.

Kotlin v1.2 was released on November 28, 2017. Sharing code between JVM and Javascript platforms feature was newly added to this release

The name comes from Kotlin Island, near St. Petersburg Russia .

  • Java or Kotlin for Android development

In case of android app development Java is most favourite language of many developers .But did you know that kotlin is ready to challenge Java’s leadership in the Android application development and a lot of developers are switching from java to kotlin.

Let’s have a detailed comparison of java and Kotlin.

  1. Java

In case of android development Java is mostly used and favourite of many developers also Android itself is written in Java. Java is a object oriented programming language that holds the cap of second most active programming language ion Github. And probably one of the oldest programing language around 20 years of active.

Pros of Java

  • Simple : Java is easy to learn,use,write,compile and debug than alternative programming languages.
  • Compilation speed is high
  • In case of cross platform applications Java is a far better choice .
  • Most of the android applications are running on Java and A lot of java libraries are available for android SDK
  • Java has a large open-source ecosystem, partly as a result of Google’s adoption of the Java Virtual Machine (JVM) for Android;
  • In comparison to Kotlin  Java applications are more compact and lighter
  • The build & compilation speed is high than Kotlin  
  • Lot of tutorials and online materials are available  for android development using java ,In case of Kotlin as its a new language the materials are limited.

Cons of Java

  1. Java has limitations that cause problems with Android API design
  2. As compare with Kotlin , More code is needed to be written in java .
  3. It is slower and more memory consuming .than many other language

Kotlin

Kotlin was designed by programmers from JetBrains to add some modern features to Java that come in handy in mobile development. Kotlin is an open source, statically typed language based on Java Virtual Machine (JVM), but you can also compile it to JavaScript or Native for building code that can run on iOS. All it takes is installing the Kotlin Plugin and letting it configure your project.

Pros of Kotlin

  • Fully compatible and easy to convert from java to Kotlin : Just install Kotlin plugin in Android SDK and sync gradle then click Convert to convert java files to Kotlin
  • All major java frameworks started supporting Kotlin (Like Spring started support Kotlin from Spring 5)
  • Well management in NullPointerException : Introduction of !! operator aimed to eliminate NullPointerException’s the  code.
  • Fewer chance to get errors in code and in compare to java less coding needed.
  • Easy to switch from Java to Kotlin
  • All java libraries are fully compatible with Kotlin
  • Compilation time in kotlin are improving well and almost same as that of Java.

Cons of Kotlin

  • Slower compilation speed than Java
  • Switching entire team from Java to Kotlin might be challenging
  • The availability of developer community and finding answers for questions are limited , but its growing fastly.
  • In android studio auto_completion are working slower than Java.

Kotlin version history

  • Kotlin v1.0 : Official stable version of Kotlin released on February 15 ,2016.
  • Kotlin v1.2 : Added the possibility to reuse code between the JVM and JavaScript,new libraries introduced to help cross platform applications
  • Kotlin v1.2.2 :Adds support for Gradle build cache
  • Kotlin v1.2.6 : latest version available and released on Aug 1, 2018.
  • Kotlin v1.2.3 : Adds a new declaration in the standard library, which imitates the suspend
  • Kotlin v1.3 : upcoming version
  • Conclusion

In my opinion If you are a beginner in android development and you have a decent knowledge in Java , its better to start with Kotlin instead of Java. But of course you might have some  good knowledge in Java.

Kotlin is now an Official language for android development and a lot of brands like Amazon,pintrest and netflix are already converted to kotlin.  As the article name says it is a new era in android development and Kotlin is only beginning to ride in the growth curve. With support from Google and heavy-hitting brands making the switch kotlin quickly proving itself to be a superior programming language for android application development.

Some Useful tutorials

Java or Kotlin for Android development

In case of android app development Java is most favourite language of many developers .But did you know that kotlin is ready to challenge Java’s leadership in the Android application development and a lot of developers are switching from java to kotlin.

Let’s have a detailed comparison of java and Kotlin.

 


  • Java

In case of android development Java is mostly used and favourite of many developers also Android itself is written in Java. Java is a object oriented programming language that holds the cap of second most active programming language ion Github. And probably one of the oldest programing language around 20 years of active.

Pros of Java

  • Simple : Java is easy to learn,use,write,compile and debug than alternative programming languages.
  • Compilation speed is high
  • In case of cross platform applications Java is a far better choice .
  • Most of the android applications are running on Java and A lot of java libraries are available for android SDK
  • Java has a large open-source ecosystem, partly as a result of Google’s adoption of the Java Virtual Machine (JVM) for Android;
  • In comparison to Kotlin  Java applications are more compact and lighter
  • The build & compilation speed is high than Kotlin  
  • Lot of tutorials and online materials are available  for android development using java ,In case of Kotlin as its a new language the materials are limited.

Cons of Java

  • Java has limitations that cause problems with Android API design
  • As compare with Kotlin , More code is needed to be written in java .
  • It is slower and more memory consuming .than many other languages

 

 


  • Kotlin

Kotlin was designed by programmers from JetBrains to add some modern features to Java that come in handy in mobile development. Kotlin is an open source, statically typed language based on Java Virtual Machine (JVM), but you can also compile it to JavaScript or Native for building code that can run on iOS. All it takes is installing the Kotlin Plugin and letting it configure your project.

Pros of Kotlin

  • Fully compatible and easy to convert from java to Kotlin : Just install Kotlin plugin in Android SDK and sync gradle then click Convert to convert java files to Kotlin
  • All major java frameworks started supporting Kotlin (Like Spring started support Kotlin from Spring 5)
  • Well management in NullPointerException : Introduction of !! operator aimed to eliminate NullPointerException’s the  code.
  • Fewer chance to get errors in code and in compare to java less coding needed.
  • Easy to switch from Java to Kotlin
  • All java libraries are fully compatible with Kotlin
  • Compilation time in kotlin are improving well and almost same as that of Java.

Cons of Kotlin

  • Slower compilation speed than Java
  • Switching entire team from Java to Kotlin might be challenging
  • The availability of developer community and finding answers for questions are limited , but its growing fastly.
  • In android studio auto_completion are working slower than Java.

 

  • Conclusion

 

In my opinion If you are a beginner in android development and you have a decent knowledge in Java , its better to start with Kotlin instead of Java. But of course you might have some  good knowledge in Java.

Kotlin is now an Official language for android development and a lot of brands like Amazon,pintrest and netflix are already converted to kotlin.  As the article name says it is a new era in android development and Kotlin is only beginning to ride in the growth curve. With support from Google and heavy-hitting brands making the switch kotlin quickly proving itself to be a superior programming language for android application development.