--

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

Wednesday, 13 June 2018

Kotlin - Chapter 5 - Model View Presenter (MVP) pattern

The Model View Presenter pattern is an architectural pattern based on the Model View Controller (MVC) pattern that increases the separation of concerns and facilitates unit testing.
It creates three layers, Model, View, and Presenter, each with a well defined responsibility. The MVP pattern separates the data model, from a view through a presenter.

The Model
Accommodating models (POJO class), data from various sources (database, server results, cache, Android file system, etc.).

The View
View is responsible for visual display of applications, along with data input by users. This part should NOT under any circumstances process the data. Its function is only to detect the input (e.g. touch or swipe) and visualization.

The Presenter
Presenter is responsible for passing of data between two layers, and thus the analysis and interaction. Such division allows substitution of code parts, proper testing and connects layers as interfaces.

Android MVP Guidelines
  1. Activity, Fragment and a CustomView act as the View part of the application.
  2. The Presenter is responsible for listening to user interactions (on the View) and model updates (database, APIs) as well as updating the Model and the View.
  3. Generally, a View and Presenter are in a one to one relationship. One Presenter class manages one View at a time.
  4. Interfaces need to be defined and implemented to communicate between View-Presenter and Presenter-Model.
  5. The Presenter is responsible for handling all the background tasks. Android SDK classes must be avoided in the presenter classes.
  6. The View and Model classes can’t have a reference of one another.
Having covered the theory of MVP architecture, let’s build an android MVP app now. I have developed a very simple application to demonstrate MVP. When user click ‘Tap me’ button, I am showing “Hello, Kotlinzers!!!”  popup message,

We have to create 3 packages such as model, presenter, view.

When to follow MVP design pattern ?
MVP makes it easier to test your presenter logic and to replace dependencies. But using MVP also comes with a cost, it makes your application code longer. Also as the standard Android templates at the moment do not use this approach, not every Android developer will find this code structure easy to understand.
Model Layer
The Model layer is responsible for handling the business logic. It holds an popup message shown to the user, and a reference to the Presenter.

      We have to create IBaseView.kt & IBasePresenter.kt interfaces to implement to communicate between View-Presenter and Presenter-Model.

interface IBasePresenter {
fun clickMe()
}


interface IBaseView {
fun clickSuccess(text: String)
}

Let us implement IBaseView interface in Activity,

        Because Android doesn't permit the instantiation of an Activity, the View layer will be instantiated for us. We are responsible for instantiating the Presenter and Model layers. Unfortunately, instantiating those layers outside the Activity can be problematic.
       It is recommended to use a form of dependency injection to accomplish this. Since our goal is to concentrate on the MVP implementation, we will take an easier approach. This isn't the best approach available, but it is the easiest to understand.
I have shared this source code on GitHub

Happy Coding!!!

Thursday, 24 May 2018

Kotlin - Chapter 4 - Room DataBase framework

Saving data in local DB using Room

Room persistence library introduced at Google I/O 2017 basically is not a database it just acts as middle man between SQLite and Application layer. By caching required pieces of data from web services.
If the device cannot access the network, the user can still access that content while they are offline. Any user-initiated content changes are then synced to the server after the device is back online.
Room provides enhanced security, easy access, easy to setup and quick to get started with new database. All the DML (Data Manipulation Language) commands are now annotated except SELECT command which works with @Query.

Components of Room


We have 3 components they are
Entity : a model class annotated with @Entity where all the variable will become column name for the table and name of the model class becomes name of the table.
Database: This is an abstract class where you define all the entities that means all the tables that you want to create for that database.
Dao (Data Access Objects): This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here.
Apply the kotlin-kapt plugin in the app.gradle file,
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
Add the kapt dependency in the app.gradle file,
dependencies {
   implementation fileTree(include: ['*.jar'], dir: 'libs')
   implementation "android.arch.persistence.room:runtime:$room_version"
   annotationProcessor "android.arch.persistence.room:compiler:$room_version"
   kapt "android.arch.persistence.room:compiler:$room_version"
...
}
       First of all let’s create our model class where all it’s variable name will become the column name and name of model class will become the table name.

      Now let’s create our Dao interface which contains the list of operation that we would like to perform on table.
Finally let’s create our database with version number.
@Database(entities = arrayOf(User::class), version = 1)
abstract class UserDatabase : RoomDatabase() {
abstract fun userDAOAccess(): IUserDao
}
We can insert test user to Room DB by calling insert() function,

       One great feature that Room supports is LiveData that means you can observe the changes and as soon as any data gets changed in the database you get the response. One more advantage is that LiveData observable are lifecycle aware component which gives response only when your activity or fragment is either in onStart or onResume state.
Now save and run the App. You can download the full source code for this project on GitHub
Happy coding !!!

Monday, 30 April 2018

Kotlin - Chapter 3 - Showcasing Viewpager using Kotlin


ViewPager in Android allows the user to flip left and right through pages of data. Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows.
This post shows you how to do screen slides with a ViewPager provided by the support library in Kotlin. ViewPagers can animate screen slides automatically.
You’ll divide the ViewPager implementation into three parts:
  1. Adding the ViewPager
  2. Creating an Adapter for the ViewPager
  3. Wiring up the ViewPager and the Adapter
We have to add android.support.design.widget.TabLayout & android.support.v4.view.ViewPager in layout file same as Java.


ViewPager is only available through the Android Support Library. The Android Support Library is actually a set of libraries that provide backward compatible implementations of widgets and other standard Android functionality.
These libraries provide a common API that often allow the use of newer Android SDK features on devices that only support lower API levels. You should familiarize yourself with the Support Library and Support Library Packages.
We need to create our PageAdapter. This is a class that inherits from the FragmentPageAdapater class. In creating this class, we have two goals in mind:
  1. Make sure the Adapter has our fragment list
  2. Make sure it gives the Activity the correct fragment
By extending FragmentPagerAdapter, we can add multiple fragments to the ViewPager. We need to implement setupViewPager method in the ViewPagerActivity.

supportFragmentManager is equivalent to the getSupportFragmentManager() method you would use in Java and viewPager.adapter = pagerAdapter is the same as viewPager.setAdapter(pagerAdapter).
Note : The FragmentPagerAdapter is the more general PageAdapter to use. This version does not destroy Fragments it has as long as the user can potentially go back to that Fragment. The idea is that this PageAdapter is used for mainly "static" or unchanging Fragments. If you have Fragments that are more dynamic and change frequently, you may want to look into the FragmentStatePagerAdapter. This Adapter is a bit more friendly to dynamic Fragments and doesn't consume nearly as much memory as the FragmentPagerAdapter.
The output must be,

FragmentPagerAdapter or FragmentStatePagerAdapter?
There are two types of standard PagerAdapters that manage the lifecycle of each fragment: FragmentPagerAdapter and FragmentStatePagerAdapter. Both of them work well with fragments, but they are better suited for different scenarios:
  1. The FragmentPagerAdapter stores the fragments in memory as long as the user can navigate between them. When a fragment is not visible, the PagerAdapter will detach it, but not destroy it, so the fragment instance remains alive in the FragmentManager. It will release it from memory only when the Activity shuts down. This can make the transition between pages fast and smooth, but it could cause memory issues in your app if you need many fragments.
  2. The FragmentStatePagerAdapter makes sure to destroy all the fragments the user does not see and only keep their saved states in the FragmentManager, hence the name. When the user navigates back to a fragment, it will restore it using the saved state. This PagerAdapter requires much less memory, but the process of switching between pages can be slower.

Now save and run the App. You can download the full source code for this project on GitHub

Happy Coding !!!

Tuesday, 10 April 2018

Kotlin - Chapter 2 - Developing Android Apps using Kotlin

Calling REST API in Kotlin


       I have implemented REST API call using HttpURLConnection & Retrofit API. We will create a connection between Android App and server at certain period then receive the data request from Android App to server.

Rest API and JsonObject Model :

      REST APIs is often used in mobile applications, social networking Web sites, mashup tools, and automated business processes. The REST style emphasizes that interactions between clients and services is enhanced by having a limited number of operations.

Using HttpURLConnection :

A URLConnection with support for HTTP-specific features.

Uses of this class follow a pattern:

  • Obtain a new HttpURLConnection by calling URL.openConnection() and casting the result to HttpURLConnection.
  • Prepare the request. The primary property of a request is its URI. Request headers may also include metadata such as credentials, preferred content types, and session cookies.
  • Optionally upload a request body. Instances must be configured with setDoOutput(true) if they include a request body. Transmit data by writing to the stream returned by URLConnection.getOutputStream().
  • Read the response. Response headers typically include metadata such as the response body's content type and length, modified dates and session cookies. The response body may be read from the stream returned by URLConnection.getInputStream(). If the response has no body, that method returns an empty stream.
  • Disconnect. Once the response body has been read, the HttpURLConnection should be closed by calling disconnect(). Disconnecting releases the resources held by a connection so they may be closed or reused.

Response Handling :

       HttpURLConnection will follow up to five HTTP redirects. It will follow redirects from one origin server to another. This implementation doesn't follow redirects from HTTPS to HTTP or vice versa.
If the HTTP response indicates that an error occurred, URLConnection.getInputStream() will throw an IOException. Use getErrorStream() to read the error response.



var - something that will vary with time. (Mutable )

val - for a value that won’t change. (Immutable - i.e. read-only)

Calling getUsers() function in doInBackground of inner class AsyncTask.



Note :
If you have to send GET/POST requests over HTTPS protocol, then all you need is to use javax.net.ssl.HttpsURLConnection instead of java.net.HttpURLConnection. Rest all the steps will be same as above, HttpsURLConnection will take care of SSL handshake and encryption.

Using Retrofit API

     Retrofit is type-safe HTTP client for Android and Java by Square, Inc. It is an open source library which simplifies HTTP communication by turning remote APIs into declarative, type-safe interfaces. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST based web service. It automatically serializes the JSON response using a POJO which must be defined in advanced for the JSON Structure. 

     REST Client in our case is the Retrofit library that is used on the client side (Android) to make HTTP request to REST API, in our case, The USER API and also process the response. A REST API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST. 

     We can also simply say that a RESTful API is an application program interface (API) that uses HTTP requests to GET, PUT, POST and DELETE data. We have to initialize Retrofit client by setting up baseUrl, addConverterFactory. 

By Query parameters can also be added to a method. creating interface for fetching list of users using gson library,

interface IUser{
@GET ("users")
fun getAllUsers() : Call<RetroUser>
}

You can use replacement blocks and query parameters to adjust the URL. A replacement block is added to the relative URL with {}. With the help of the @Path annotation on the method parameter, the value of that parameter is bound to the specific replacement block.




       A Retrofit class which generates an implementation of the UserService interface. The above sample code would be inside the Retrofit class and this is how it creates an instance of Retrofit and implements the getAllUsers() method that’s in the IUser Interface. By calling loadUsers() function in onCreate() override method.


Using simple service URL to fetch user details.
URL : https://reqres.in/api/users
The output would be,

Now save and run the App. You can download the full source code for this project on GitHub

Happy Coding !!!

Friday, 2 February 2018

Kotlin - Chapter 1 - Exploring Kotlin for Android App development

Welcome to Kotlin World !!!



What Kotlin means ?



Kotlin is a statically typed programming language and development language from JetBrains which is the company behind the IntelliJ Java IDE (i.e. Android Studio is based on) that runs on the Java virtual machine and also can be compiled to JavaScript source code.


Note : Kotlin isn't a programming language on its own; it's a new way to write code that uses Java to run.


At Google I/O 2017 in April, Google announced that Kotlin would forever more be supported as a first class programming language for Android. And the recently released Android Studio 3.0 supports Kotlin out of the box!

Why Kotlin is good?


  • Kotlin comes from industry, not academia. It solves problems faced by working programmers today.
  • Kotlin costs nothing to adopt! It’s open source, a high quality, one-click Java to Kotlin converter tool, and a strong focus on Java binary compatibility. You can convert an existing Java project one file at a time.
  • No particular philosophy of programming, such as overly functional or OOP styling and also Semicolon free language.
  • Kotlin programs can use all existing Java frameworks and libraries, even advanced frameworks that rely on annotation processing. 
  • No runtime overhead. The standard library is small and tight: it consists mostly of focused extensions to the Java standard library. 
  • No new keyword while initialization any object.  


Getting started with Android and Kotlin


Let walk through creating a simple Kotlin application for Android using Android Studio.

Installing the Kotlin plugin



The Kotlin plugin is bundled with Android Studio starting from version 3.0.

If you use an earlier version, you'll need to install the Kotlin plugin. Go to File | Settings | Plugins | Install JetBrains plugin… and then search for and install Kotlin.

If you are looking at the "Welcome to Android Studio" screen, choose Configure | Plugins | Install JetBrains plugin after that restart the IDE.

First let's create a new project. Choose Start a new Android Studio project or File | New project.
Android Studio 3.0 offers an option to enable Kotlin support on this screen. You can check this option and skip the "Configuring Kotlin in the project".



In Android Studio 3.0, you can choose to create the activity in Kotlin right away, so you can skip the "Converting Java code to Kotlin" step. Earlier versions will create an activity in Java, and you can use the automated converter tool to convert it.

Building and publishing the Kotlin application for Android


You can make a release of the application and sign it similarly to what you do for an Android application written in Java. Kotlin has a rather small runtime file size: the library is approximately 964KB. This means Kotlin adds just a little to .apk file size.

Kotlin compiler produces byte-code, thus there really is no difference in terms of look and feel of Kotlin applications versus those written in Java.

How Kotlin stands out ?


Kotlin is directly filled the gap of modern programming language for Android application development like how Swift language does for iOS development.


1. Concise to reduce the amount of boilerplate code you need to write.
We can create a POJO with getters, setters, equals(), hashCode(), toString(), and copy() with a single line.
  • No need hashCode(), equals(), toString(), and copy()
  • Compiler automatically create these internally, so it also leads to clean code.

data class Developer(val name: String, val age: Int)
Requirements that data classes need to fulfil:
  • The primary constructor needs to have at least one parameter.
  • All primary constructor parameters need to be marked as val or var
  • Data classes cannot be abstract, open, sealed or inner.

2. No null pointer exceptions (NPE) in Kotlin
Kotlin type system helps you avoid null pointer exceptions (NPE). Research languages tend to just not have null at all, but this is of no use to people working with large codebases and APIs which do.
We have to write safer code to avoid NullPointerExceptions in our app.
var message: String = null      // Compile-time error
var message: String? = null     // Okay
If something is null, I want to give it a value, but otherwise just leave it alone.
// Java
           if (people == null) {
               people = new ArrayList();
           }
           return people;
// Kotlin
           return people ?: emptyArrayList()
The Elvis Operator (?:) looks like the ternary conditional operator in Java, but works differently.
If you’re absolutely sure a nullable object is not null, feel free to use the !! operator to dereference your object.
tabLayout = findViewById<TabLayout>(R.id.tabs)
        tabLayout!!.setupWithViewPager(viewPager)

3. No need findViewById using android-extensions
Kotlin (specifically Android Extensions) do the heavy lifting for you. apply plugin: 'kotlin-android-extensions' in app.gradle
For the layout filename activity_main.xml, we'd need to import
import kotlinx.android.synthetic.main.activity_main.*
txtTitle.text = "Hello Kotlin"
There is no more view binding. Internally the compiler creates a small hidden cache. Moreover Activity or Fragment giving us the synthetic property to use the view. Lazy initialized i.e. when you use the view in the code. Next time you use the same view it will fetch it from cache.

4. Zero-overhead lambdas
Functional programming support with zero-overhead lambdas and ability to do mapping, folding etc over standard Java collections. The Kotlin type system distinguishes between mutable and immutable views over collections.
Higher Order Function - passed as an argument to another function. Beautifying even the ugliest click handlers,
mButton.setOnClickListener {
   // Your click logic
}
Cut to the main logic & code so clean and simple.

5. 100% inter-operable with Java™ (Automatic conversion)
Interoperable to leverage existing frameworks and libraries of the JVM with 100 percent Java interoperability.
Kotlin is a programming language made by developers for developers, it’s designed to make your life as easy as possible. The Kotlin plugin even has a handy tool that allows you to convert a Java source file to Kotlin.
Open the DetailActivity.java class and go to Code\Convert Java File to Kotlin File.




Click OK on the Convert Java to Kotlin screen. This will replace the Java file with a Kotlin. That’s it. You’ve converted a Java class into a Kotlin class.

6. Extend function without extends or implement keyword
class MainActivity : AppCompatActivity() {
  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)
  }
}
Inheritance- No “extends” & “implements”, Replaced with a “:”

7. Free Functions (Functions without belong to any class)
Functions or variables can be declared at the top level in a file (*.kt) without any class. By default static in nature without any class holding them.
We can write free functions and access them from another Kotlin class or file directly (without Class name). But, functions come with access specifiers to control the visibility.

8. No if/else if/else/switch blocks
Replacing simple if/else if/else/switch blocks with ‘when’ keyword
In JAVA

  if (firstName.equals("Dan")) {
               person.setTeam(programmers);
           } else if (lastName.equals("Dihiansan")) {
               person.setTeam(designers);
           } else {
               person.setTeam(others);
           }

switch (firstName) {
               case "Dan": person.setTeam(programmers)
               break;
               case "Jay": person.setTeam(programmers)
               break;
               case "Jamie": person.setTeam(designers)
               break;
               default:
               person.setTeam(others)
           }

In Kotlin
when {
               firstName == "Dan"       -> person.team = programmers
               lastName == "Dihiansan" -> person.team = designers
               else         -> person.team = others
           }

when (firstName) {
               "Dan", "Jay" -> person.team = programmers
               "Jamie" -> person.team = designers
               else -> person.team = others
           }


9. apply() for Grouping Object Initialization
//Don't
val dataSource = BasicDataSource()
           dataSource.driverClassName = "com.mysql.jdbc.Driver"
           dataSource.url = "jdbc:mysql://domain:3309/db"
           dataSource.username = "username"
           dataSource.password = "password"
//Do
           val dataSource = BasicDataSource().apply {
               driverClassName = "com.mysql.jdbc.Driver"
               url = "jdbc:mysql://domain:3309/db"
               username = "username"
               password = "password" }

It helps to group and centralize initialization code for an object. apply() is often useful when dealing with Java libraries in Kotlin.

10. Returning Two Values from a Function
Destructuring is the convenient way of extracting multiple values from data.


fun getDeveloper(): Developer {
// some logic
return Developer(name, age)
}
val (name, age) = getDeveloper()
// do something with the key and the value
}
data class Developer(val name: String, val age: Int)
// Now, to use this function: Destructuring Declarations and Maps
for ((key, value) in map) {}
Hope I covered some basic cool stuffs about Kotlin programming language. I have developed sample Android application with Android key features in Kotlin. I keep updating in next chapters of Kotlin.

References


Kotlin interactive programming  
Happy Coding !!!!