Kotlin Sign up and Sign in with Retrofit Tutorial

Volkan YILMAZ
2 min readOct 26, 2019

--

Kotlin is rapidly gaining popularity among android developers. It is native mobile language and it has lots of advantages over Java. Java is 20 years old and since each new version should compatible with old versions, it prevents Java to progress more. Kotlin is however very young language and interoperable with Java. Same tasks can be done with less effort and with short code blocks. Kotlin compiler is more advanced and safer. Moreover, a lot of IDEs support Kotlin language now.

Retrofit is REST client for android. We use it for connection with API. It makes our task relatively easy to retrieve data and upload JSON objects. Retrofit uses the OkHttp library for HTTP requests. To use Retrofit library, we need to add some libraries into our project. In order to do this, you just need to add them in build.gradle file:

build.gradle file

We need the Internet permission in Android Manifest.xml.

AndroidManifest.xml file

After you add them successfuly, you might create an API package and inside that a RetrofitClient.kt class. We initialize Retrofit Instance. We will use it to determine requests and API connection. This file should look like:

In interface you can determine the call structure. We determine there will be a JSON object coming from backend. POST makes a POST request to relative URL of the endpoint. We should determine models or data classes.

In models package, we can create UserBody data class simply:

In this example, we just request 5 fields when a user wants to register to our system. In another example, I use sign in and we request 2 fields in login screen. For this function we just need a data class like this:

When you validate your user credentials, you can call signup function in register activity:

I put Toast messages to highlight each function. And sign in function should like this:

--

--