Showing posts with label Kotlin Development. Show all posts
Showing posts with label Kotlin Development. Show all posts

July 10, 2018

How to make an API call in android Kotlin using retrofit library

     On this blog I am going to explain How to make an API call with the Help of Retrofit Library on Kotlin. Here is the steps to integrated API call using retrofit library in android Kotlin. With the help of and Interface class I am calling this API.


        First you need to add the dependency library on your app level build.gradle file.

compile 'com.google.code.gson:gson:2.8.1'
compile 'com.squareup.okhttp3:okhttp:3.4.1'
compile('com.squareup.retrofit2:retrofit:2.1.0') {
    exclude module: 'okhttp'
}
compile 'com.squareup.retrofit2:converter-gson:2.2.0'


I am having a Constants.java class there I defiled my Base Url of my API like,


class Constants {
    companion object AppConstants {
        const val BaseUrl = "http://api.shidhin.net/";
    }
}


                      Next Step, I Created a new class ApiClient.java class, which we are used to invoke the API Call. Here is My ApiClient.java class,


class ApiClient {
    companion object {
        fun create(): ApiInterface {
            val TIMEOUT:Long = 2 * 60 * 1000
            val retrofit = Retrofit.Builder()
                    .client(OkHttpClient().newBuilder().connectTimeout(TIMEOUT, TimeUnit.SECONDS).readTimeout(TIMEOUT, TimeUnit.SECONDS).writeTimeout(TIMEOUT, TimeUnit.SECONDS).build())
                    .addConverterFactory(GsonConverterFactory.create()).baseUrl(Constants.AppConstants.BaseUrl)
                    .build()
            return retrofit.create(ApiInterface::class.java)
        }
    }

    val apiServices by lazy {
        ApiClient.create()
    }

}


                                  Next Step, I Created a new Interface ApiInterface.java , which which will  helps to API Call.  On this Class we will define the API functions. On this I have POST method with Header value, Here is My ApiInterface.java class,


interface ApiInterface {

    @POST("api/shops/AddNewShopDetails")
    @Headers("Content-Type: application/json")
    fun addShopDetails(@Body  body: JsonObject): Call<CommonServiceResponse>
}


       For the above API calls we used a class  CommonServiceResponse to parse the API response, Here is those classes, Based on the API response the structure of these class can be changed,

Class to parse addShopDetails API

class CommonServiceResponse {
    @SerializedName("status")
    public var status: Boolean? = null
    @SerializedName("message")
    public var message: String? = null
}

                    Now we added all the Class files we needed to the API Integration. Now I will show you How to invoke API calls on our Application.







API Call:  addShopDetails


val request = JsonObject()
request.addProperty("token", token)
request.addProperty("shopName", shopName)
request.addProperty("shopAddress", shopAddress)
ApiClient().apiServices.addShopDetails(request).enqueue(object : Callback<CommonServiceResponse> {
    override fun onResponse(call: Call<CommonServiceResponse>?, response: Response<CommonServiceResponse>?) {
        if (response != null && response.body() != null ) {
            
             //Here Comes the code to parse the result
} } override fun onFailure(call: Call<CommonServiceResponse>?, t: Throwable?) { Log.v("ApiFailure", "api Call Failure") } })
---------------
Thanks For Reading, Wish you a Happy Coding....

June 19, 2018

Custom Dialog in Kotlin

               On this blog I am going to explain How to create and display a custom Dialog on Kotlin. Here I am going to display a dialog with custom Title and Message which I pass to the dialog. 


colors.xml 
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#DB3236</color>
    <color name="colorPrimaryDark">#C52D30</color>
    <color name="colorAccent">#111111</color>
    <color name="iconColor">#9a9999</color>
    <color name="Black">#000000</color>
    <color name="White">#fff</color>
    <color name="LightBlack">#111111</color>
    <color name="Gray">#777777</color>
    <color name="DarkGray">#444444</color>
    <color name="MediumGray">#dddddd</color>
    <color name="LightGray">#f5f5f2</color>
</resources>


styles.xml 
<resources>
    <style name="App_TextView_Normal">
        <item name="android:textColor">@color/DarkGray</item>
        <item name="android:textSize">14sp</item>
        <item name="android:fontFamily">@font/biryani</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
    </style>
    <style name="App_TextView_Title">
        <item name="android:textColor">@color/DarkGray</item>
        <item name="android:textSize">16sp</item>
        <item name="android:fontFamily">@font/biryani</item>
        <item name="android:gravity">center</item>
        <item name="android:textStyle">bold</item>
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">match_parent</item>
    </style>

    <style name="App_TextView_Button">
        <item name="android:textColor">@color/DarkGray</item>
        <item name="android:textSize">16sp</item>
        <item name="android:fontFamily">@font/fjalla_one</item>
        <item name="android:gravity">center</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">match_parent</item>
        <item name="android:minHeight">40dp</item>
    </style>
</resources>


rounded_white_bg.xml 
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <shape android:shape="rectangle">
            <stroke android:width="1px" android:color="@color/White" />
            <solid android:color="@color/White" />
            <corners android:radius="10dp"/>
        </shape>
    </item>
</layer-list>


info_dialog.xml 

This is the dialog layout file. You can remove the background colors, text colors and styles.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/rounded_white_bg"
    android:paddingTop="5dp">
    <TextView
        android:id="@+id/txtTitle"
        style="@style/App_TextView_Title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:paddingTop="10dp"
        android:text="@string/Title" />
    <TextView
        android:id="@+id/txtMessage"
        style="@style/App_TextView_Normal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/Description"
        android:gravity="center|top"
        android:minLines="2"
        android:padding="5dp"/>

    <TextView
        style="@style/App_TextView_Normal"
        android:layout_width="match_parent"
        android:layout_height="1px"
        android:layout_marginTop="1px"
        android:layout_marginBottom="1px"
        android:background="@color/MediumGray"/>

    <Button
        android:id="@+id/btnOK"
        style="@style/App_TextView_Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/White"
        android:layout_marginRight="10dp"
        android:layout_marginLeft="10dp"
        android:textColor="@color/colorPrimary"
        android:text="@string/OK" />
</LinearLayout>



InfoMessageDialog.kt

This is the kotlin class file, We will pass the "Title" and "Message" to the Dialog class and it will be displayed on the class. 


class InfoMessageDialog(context: Context, private var title : String, private var message : String)  : Dialog(context) {

    var mContext: Context
    var mTitle : String
    var mMessage :String

    init{
        this.mContext = context
        this.mTitle = title        this.mMessage = message    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        requestWindowFeature(Window.FEATURE_NO_TITLE)
        setContentView(R.layout.info_dialog)
        window!!.setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
        setCanceledOnTouchOutside(true)

        var txtTitle = findViewById<TextView>(R.id.txtTitle)
        var txtMessage  = findViewById<TextView>(R.id.txtMessage)
        var btnOK  = findViewById<Button>(R.id.btnOK)

        txtTitle.setText(mTitle)
        txtMessage.setText(mMessage)

        btnOK.setOnClickListener(View.OnClickListener {             dismiss()
        })
    }
}


We can show this dialog using,

Fragment Page,


InfoMessageDialog(activity, getString(R.string.No_Network_Title), getString(R.string.No_Network_Message)).show();


Activity Page,

InfoMessageDialog(this, getString(R.string.No_Network_Title), getString(R.string.No_Network_Message)).show();





---------------
Thanks For Reading, Wish you a Happy Coding....

Splash Screen on Kotlin language

         On this blog I am going to explain how to show a splash screen using Handler. You can find more about Handler from Here.

Here I am using a delay of 4000 MS (4 Seconds)


Here I am using  postDelayed function for this,

fun postDelayed(r: Runnable!, delayMillis: Long): Boolean


Sample Code

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_splash)
   
    Handler().postDelayed({
                 //Here Comes the code to execute after the time delay
      }, 4000)
}




---------------
Thanks For Reading, Wish you a Happy Coding....






Create new Kotlin Project

                   
On this blog I am going to explain How to setup new Kotlin project on Android Studio. To setup new project on Kotlin on Android project we need Android Studio version 3.0 or more. For older version of studio we can user Pligins. You can able to download by selecting "Install JetBrains plugin". 

Here is the steps to start new Android Project with Kotlin Support.


Goto File => New => NewProject



While select New Project you can see the Create New Project window, 
              

 You can add the project details such as Application Name, Company domain, Project Location, Package name etc. And By selecting "Include Kotlin Support" you can enable the Kotlin support on your Project.

After This Screen while tap on "Next" button it will show the screen to Select the Target Device,
              

This screen will allow you to choose the Android  Target Device you need, While tap on Next button it will show the Choose Activity Screen
              

On this screen you can select the Type of Activity we need on the Application. While Tap on Next button it will show the screen to Configure the selected Activity page.
              

On this Screen we can Add the Activity Name and the layout name. And while Tap on Finish button it will Create the New Project with your Configurations. While tap on finish button it will setup your first project. Here is the project window.




---------------
Thanks For Reading, Wish you a Happy Coding....