Kotlin

Kotlin is statically typed programming language for modern multiplatform applications created by JetBrains.

Kotlin works side by side with Java and C++ on Android. So you can keep your existing code, continue to use the various Android libraries, and incrementally add Kotlin code to your project.Kotlin is a drop-in replacement you can use bi-directionally.You can call into the Java language from Kotlin, and you can call into Kotlin from the Java language.

 

Why Kotlin?

Reduce the boilerplate code.

Create a POJO with getters, setters,equals()hashCode() toString() and copy() in a single line:

Avoid NullPointerException.

Get rid of those pesky NullPointerExceptions, you know, The Billion Dollar Mistake.

Leverage existing libraries for JVM and Android.

Use any existing library on the JVM, as there’s 100% compatibility, including SAM support.

Once you start using the language you really go to appreciate it and that’s because it’s built by this company that has these millions of lines of Java.They Intimately know the pains and the things that cause them problems.The whole language is designed very programmatically to try and fixed those things.

Basic Syntax

So mostly we focus on understanding the syntax of Kotlin to start with and kind of the constructs that it provides. If you’ve done Java development there’s sort of this understanding of languages that this curve of understanding or maybe appreciation that you go through in almost every language.

Kotlin basic syntax

That there is no class notice that. So the great thing about kotlin is that you can just open a file and put function it so you have top-level functions. It’s not like Java that you need to have a static class and static method.You can just have a file called helper and you can distribute your function into.

Variable

We’re going to look at local properties. We don’t really talk about variables we talk about properties.There is a keyword in front of our property or local property val this denotes it is read-only.

We have the type and the name reversed is that because of a lot of time you can infer the type based on the context on the right side of the equal sign. So usually we’re calling a method referencing a field or referencing a constant here.

Kotlin is very strong in type inference, and as much as it can infer it will for you.So you don’t have to explicitly tell the type.

Create Function

Default return type of function is Unit which is kind of like void but is not.It actually an object which is essentially a singleton, a single instance of an object.If it is a Unit, You don’t have to put it there.

We have functions that are really easy, like essentially returning a single value, you can just do single expression functions.

So I omit the return type explicitly, I omit curly braces and just return the actual function that you wanna do.

Null Values

You can’t assign null in Kotlin because Kotlin tries to get rid of the nullPointerException by saying that type isn’t nullable by default, But there are times when you want to have a type that is nullable for whatever reason.

You can add a question mark(?), and then that will give you the ability to assign null to that type.Now normally when you’re working with kotlin, you probably don’t want to do this.You probably don’t want to have nullable types, But Java can be null.So if I create a function here that is for instance,

 

 

name can be null.So there are two ways you can solve this.

1 name, not null.if condition.

2 The shorter way is just to use the safe operator or Elvis Operator.

When we have a nullable reference name, we can say “if name is not null, use it, otherwise use some non-null value x“:

Class

I can create classes.

Create a class that has two properties and these properties are immutable val means immutable.var means mutable that means i can read and write to it .I’ve also created a constructor so every time i create an instance of this class i have to pass in the two values.

There is no getId or setId we have properties you don’t really use the conventions of gatter or setter.

Now notice that I don’t have any open colon, open brackets, close brackets that are as simple as I can do create a class.

Create object

There is no need for the new keyword

Data Classes

The compiler automatically derives the following members from all properties declared in the primary constructor:

  • equals()/hashCode() pair,
  • toString() of the form "Person(id=1, name=Homen)"
  • componentN() functions corresponding to the properties in their order of declaration,
  • copy()

You’ll say not big deal any good IDE that’s can generate for you but does it also maintain it for you no because when I adding a new property I’ve got to go and regenerate and do I know that the code that I’ve generated is the standard or is it something that I’ve tweaked right.

Inheritance

All classes in Kotlin have a common superclass Any, that is a default super for a class with no supertypes declared

Any is not java.lang.Object  in particular, it does not have any members other than,equals() hashCode() and toString().

By default in Kotlin classes are final so, you  can not be inherited from class unless you explicitly mark it as open

Kotlin with Java Interoperability

My code in Java can reference thing in code in Kotlin, but also the code in Kotlin can reference things back in Java.Both talk to each other and it’s sort of interesting how that actually works in practice? So we have a Java code in the module. we have Kotlin code in the module.The Kotlin compiler is going to run first both source types are fed into the Kotlin compiler and the compiler is going to parse them both. 

Kotlin with Java Interoperability

If it were just a class files coming in on the class path doesn’t know anything about Where they come from and then it sees the Java source file coming and compiles that into the class files for the Java code when you then take those.

Two class file outputs and combine them. you get the combined output from both the Java and Kotlin files and you can see now why this allows you to reference in both ways

Because any Kotlin code referencing Java will compile because Kotlin Compiler is parsing both source formats. Java code referencing Kotlin will work because from Java compiler side it’s just like a library that you’re calling. it’s just class file that you referencing and then Kotlin has a standard library which is a just ton of kind of helpers.

if your developer in an Organization and potentially with tones of modules if you’re using Kotlin nobody else really has to know or care because the output of this project is just class files and transitive dependencies.

There’s no like weak implementation detail about the language and use because of that strong interoperability.

 

New features in ConstraintLayout 1.1.x

Google I/O 17   announce a new release of ConstraintLayout. But, we didn’t get so much info about what’s inside the package, only a very superficial blog post. No docs, no examples.

So, I searched around a bit, classes and did a dive into this release to check what’s new, and how they work.

Barriers

Sometimes layout can change depending on the localization. Here is a really simple example:

Constraint Layout barrier

Here we have three TextViews: Home and Office on the left and Description on the right.

A Barrier is a virtual view to which we can constrain objects. The position of a Barrier is determined by the dimensions of multiple views. In the case of our example, we don’t know whether Home or Office will be wider, so we can create a Barrier based upon the widths of these two Views. Then we can constrain Description to the Barrier.

Creating Barriers

First, we create a vertical barrier.

Next, we need to set the direction for the Barrier. In our case we want to position the Barrierrelative to the End of either Home or Office depending on whichever is the larger, so we need to specify a direction of end:

The final step in defining the Barrier is to tell it which Views we need to position it relative to. For a Barrier we need to define multiple Views as referenced IDs.

change the constraint of Descriptionto be relative to the Barrier rather than Home

Barrieris the Barrier element itself. The app:barrierDirectionattribute determines the direction of the Barrier – in this case it will be positioned at the end of the referenced Views.

The list of referenced Views is a comma separated list of the IDs of other Views within the layout (without the @+id/ qualifier).

Group

Groups, like the Barrier, are widgets with size 0. The group helps to apply some action to a set of widgets. For example, The control a visibility of a collection of widgets. When dealing with this scenario, the most common solution was to maintain yourself a  set of views inside the Activity and put all the views inside of it, controlling the visibility of the container. Now, you only need to add their ids to the Group, and the group will propagate the actions to all plugged views.

Placeholders

A place where you can move a widget.You can create a virtual view and set its content to another view within the Constraint Layout.


Constraint Layout Placeholder

Download this project from GitHub.

In this simple example, It’s grabbing whichever one you clicked on and wrapping the middle of the screen.The animation you’re seeing on the right is completely being generated by the code you see in the example.

Design a placeholder-base UI with a merge tag. You’ve defined in ConstraintLayout, make sure to use the parent tag If you want to see the UI while you’re doing it.It essentially gives you a fixed layout which you can then use in another file.So in this case, I’ve decided to have one placeholder that’s going to be my top image, a big image and then and second placeholder that’s going to be my action button.

In Main Layout I just declare the two UI elements and include the template.Essentially it produces a template that decides on how you do your layout.

Another great feature from Placeholder is to change its referenced id at runtime, allowing you to create dynamic layouts and even cool animations with considerably less effort than using other ways.

Percent Dimensions

The default behavior of widgets of width 0dp (match_constraint) is spread (configurable through the layout_constraintWidth_default property). In ConstraintLayout 1.0.x, we had a choice to change it to wrap, and in 1.1.x, we have a new value, percent, that allow us to set a widget to take the percentage of the available space.

 

So that’s it! At least what I found by myself. Like it and share if this was useful for you.

Related Post

ConstraintLayout 1.1.0: Circular Positioning

 

Fragment Tricks

  There’s a lot of information out on the web as people have used the API gotten kind of familiar with it and in some ways kind of got bitten by it.There’s a lot of complexity there.

Why use fragment at all?

If we want to group UI components, couldn’t we just create a ViewGroup or maybe a re-usable XML layout definition? Yes but the real power in fragments goes beyond grouping UI elements.They allow us to fully modularize our activity, including the lifecycle events they receive in the app state that they maintain.Treat each fragment as though it were a mini activity.

Breaking your app into different activities. Having a single monolithic activity increases the complexity of your code.

Making the creation and management of intent filters much harder and making it more difficult to maintain, test, and read your activity code. It also increases the risk of tightly coupling independent components and makes it much more likely to introduce security risks if the single activity includes both sensitive information and information that’s safe to share.

When to use Activity?

A good rule of thumb is to create a new activity whenever the context changes.For example, displaying a different kind of data while switching from viewing to entering data.

Single Activity Architecture

With a single activity architecture, you simply have one activity and you have your view for your screen number A at number A. and instead of having a new activity for your screen B, you simply swap the view.

Fragment lifecycle 

The basic lifecycle events are much the same as the parent activity.It moves through the cycle of starts, resumes, pauses and stops those same lifecycle events will be triggered within the fragment itself.In most cases, you can simply move anything that you would have put into the activity lifecycle handles into the corresponding fragment handlers.

Fragment Lifecycel

 

onCreateView : Fragment introduced a new event specifically for UI.Here, You construct or inflate your UI, hook up to any data sources, and return it you the parent activity which can then integrate it into its view hierarchy.

There’s a correspond onDestroyView handler, which is called immediately before the fragment is added to the back stack, independent of the parent activity, onDestroyView is where you should clean up any resources specifically related to the UI, such as bitmaps in memory, cursors to data, anything like that to help ensure that your app’s memory footprint isn’t bloated by data that’s not needed  when the fragment isn’t visible.

Now as soon as the fragment is returned from the back stack,onCreateView is call and you can re-create the UI and reconnect data sources before your fragment transitions through the rest of the lifecycle to become active again.And because a fragment can only exist within an activity.

We also need callbacks to tell us when a fragment is attached and detached from its parent.OnAttach is your opportunity to get a reference to the parent activity.While onDetach is the last thing that happens,

onActivityCreated This notifies our fragment that the parent activity has completed it’s onCreate handler

Fragment Tricks

I am going to be writing about a few effective patterns for using the fragment API in your apps.Some of these are going to be they may seem a little bit basic, but they’re also things that are going to help you build apps in a way that factors your code effectively, encapsulates things and, makes sure that you can keep your code clean.

Where is fragment API came from?

As Android started moving into large screen devices in honeycomb, It is realizing that there are a few specific patterns in the way that some apps are put together, especially apps of the time.You’ve got one area that’s devoted to your navigation, and you got another area that’s devoted to content.When you put these two things together, you can imagine on a small screen device you might see the navigation as on screen that advances to the content screen, and when you’re on a larger screen device you’re able to show the same thing side by side.

It was something that you could use to factor out your activity components into two separate pieces that you could show differently based on different device configurations.Now this works really well for some application like Gmail, but your app probably isn’t Gmail.If you followed the development of app design.This sort of pattern just doesn’t fit for a lot of things.

However, it’s still extremely useful for representing your application as a series of destinations.So even on a small screen device, you might have an app that looks something like this.

Fragment Transition animation

Download this project from GitHub.

We’ve got our little application that–where you can order some flowers.For each one of these screens, you can perform a replace transaction to replace the destination that you were looking at previously with the new one.Replace transaction will remove any fragment in the container and then add new fragment. So the nice thing about is that you can place these particular transaction on the back stack, and we’ll go ahead and handle that back navigation for you

Now the nice thing about this is that the content and navigation pane separation isn’t limited to just large screens. This can really help to keep your chrome stable.

In your application you have things like bars,net drawers,bottom navigation bars, any of these things that you want to keep stable and perform some consistent animations from one screen to another this really lets you do it in a way that is really difficult to accomplish with the activity  to activity transitions where you can’t preserve that kind of continuity in your UI as you navigate deeper in your app’s hierarchy.

Navigation Flows

I’m talking about those step-by-step flows that you have in your application.So when you have a checkout or a sign up or a setup wizard, the users are going to go step by step through their navigation, and then they might want to wander back using the back button and then go forward again and then when they’re all done, you want to be all done with that.You don’t want that one user to be able to go back through the checkout process again

Key to back stack management

1.Do maintain the back stack as you navigation forward(It’s so much easier to manage your back stack if you choose the direction your user is going to go on the back stack as you navigation forward).

2.Don’t , at the time the user press the back button, choose what they’re going to do.That’s a lot harder to manage. So to take advantage of this kind of thing, sometimes you need to do some synthetic back stack management that means if you have an external link into your application, some kind of deep, nested thing, they’re selecting a particular cart item.When they hit the back button, you don’t want them to go to some–the main screen, you want them to go into the category, perhaps DON’T decide on back button navigation behavior just-in-time.

Repeated commits start and stop each fragment.

If you make repeated transactions, then that means that each one of that transaction you’re going to start and stop those fragments as you execute each one in turn.So that can be really expensive right?

how do you can go ahead and maintain that back stack state?

While still not doing a whole lot of really heavyweight work as you start and stop each one of those fragments along the way? Because you have to create all those views, tear them down again, inflation.It seems like a lot of unnecessary work.

setReorderingAllowed(true) :It allows all of the execution to happen all at once without changing your fragment state. And then at the very end, we bring up all the fragments that need to be brought up and tear down all the fragments that need be torn down.and now you’re fragments don’t have to go through all that.

 

ViewGroup or Fragment?

Using a custom ViewGroup or a Fragment in these case, Is does it implement mechanism or does it implement policy? Is it an isolated widget that generates its own input events?(Is it an isolated widget, or does it connect app logic?)

Views should really only be responsible for displaying information and publishing direct user interaction events.These end up being very low level events, like button was clicked user scrolled something.

These are responsible for drawing text and these other sorts of operations that are user interaction, wheres fragments integrate with the surrounding lifecycle and they may be aware of the app components.

Fragment is really what gives context to everything  that you’re doing in your UI.(Bind to a service, communicate with your app’s data model performing a database query, so on and so forth)

So you should never use a Fragment when a View will do, but you also want make sure that you’re not adding outside dependencies to your Views. It’s definitely a code smell if you ever find yourself doing something like trying

To bind a service from a view implementation, or trying to make a network call or again, trying to integrate with anything that’s outside of the realm of just that one individual view.

But that means that there’s a whole.It means that you can’t building just something that simple as completely self-contained like button

Don’t use a Fragment when just a composite custom ViewGroup, or even just a layout resource that you can use an include tag, wild the job better.

LiveData

It’s very common that your activity or fragment observe some data, and whenever that data changes, It wants to refresh itself.It’s like your activity receives a callback, but the activity already stopped.If an activity or a fragment is stopped there is no reason to update that UI.If the activity happens to become visible again then you want to do it.

We want to share resources across multiple fragments or activities.For example, the Location of the device is the same from fragment to fragment.If you have two fragments, why do you need to create two listeners to listen to the same location?

Hence, Android create this new LiveData clause.

LiveData

LiveData is a data holder, it just holds some data.It’s like an observable but the tricky thing about it is LifeCycle aware.If you are observing a LiveData, you don’t need to unsubscribe, the right things will happen at the right times.

  • It is a Lifecycle aware Observable.
  • It is very simple to start and stop semantic.(Doesn’t matter how many observers you have or what state they are we merge all of it into one lifecycle).
  • It doesn’t have any activity or fragments inside it works with both of them. It is also really used to test LiveData because it’s’ kind os android free.
  • Android guarantee that your observable will never, ever be called in a state where you cannot run a FragmentTransaction.
  • This is very very specifically designed to work well with your Activity and Fragments.

 

How LiveData Work?

So onCreate, it called to observe, it said LiveData is observable.And as soon as the activity starts it starts receiving data changes. So whenever the LiveData value changes, android displace that event back to your observer inside the activity.

LiveData Rotate screen

On Activity Rotated.So you know that the activity will be stopped.and what happens at the same time, the LiveData happens to be updated.If that happens LiveData is not going to tell the activity about this change. Similarly, if the activity is destroyed, Android will automatically remove the subscription because that activity is gone.

Now, The activity was rotating, so you know that android is going to recreate that activity.and then we are observing the same LiveData back. As soon as the activity starts, it’s going to receive last available data.So your UI is going to have the Data before it gets a chance to draw.

LiveData onStop

If the user hits the Home button which means the activity will be stopped. Again if the LiveData changes while the activity is stopped, is not going to receive any events. Even if the data changes we are not going to tell it.

LiveData reopen app

But as soon as if the user comes back to the application, android will give it the last available data.

So this is why we call LiveData is not just a stream of events.It holds on to data so that if any observer comes, it receive the last available value. and the eventually, the user backs out of that activity, and then we remove that subscription.

LiveData Example

Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Add the Google Maven repository

To add it to your project, open the build.gradle file for your project and add the highlighted line as shown below:

Adding Components to your Project

The activity updates the UI when the new number generated.

LiveData Example

 

LifecycleOwner

MainActivity is an instance of LifecycleActivity, which can provide the state of a lifecycle. This is the class declaration:

To expose data as an observable, wrap the type in a LiveData class.LiveData is a special observable class which is lifecycle-aware, and only notifies active observers.

Add the following code to the MainActivity class, to create the subscription:

Sets the value. If there are active observers, the value will be dispatched to them.

This method must be called from the main thread. If you need set a value from a background thread, you can use postValue(Object).

RxJava vs LiveData

Key different between RxJava and LiveData.LiveData is a holder and not a stream.So we have a reference to the last value, and observer immediately receives the last value when they start to observe liveData.

And now the big different is a threading model.As you know Rxjava has a very sophisticated threading model.It’s extremely powerful but in most cases, you probably don’t need it.LiveData has everything on the main thread.

LiveData is Lifecycle aware.It knows about android life cycles, and when you want to observe a LiveData, you can pass in this LifeCycle so that it manage your subscription.The nice thing about LiveData that is that your observer, and that’s all you do. You don’t need to write onStart, onStop.

You initialize thing as more like find and forget.You initialize and you’re done.

It’s mush easier.As many of you may know the learning curve of Rxjava is super steep.It is simpler, it ‘s faster it’s lightweight, It’s well integrated with a framework.If you feel like you love reacting programming a lot, You want to bring it not only to the relation between UI and the state. You want to bring it to the business part of your application.Then you may consider the addition of RxJava, because it gives you more power.Android will actually help you to do that.Android has this extension to the library, Which gives a possibility to create LiveData from Publisher and create Publisher from LiveData.So this Integration should be quite smooth.

What is an active observer?

You can also extend the LiveData class.Because LiveData provides two really handy callbacks.

We define an active observer as an observer that’s in the STARTED or RESUMED state which is like an activity user is currently seeing.So if you have an observer in the back stack, there’s no reason to put this inactive.There’s no reason to update that activity because the user will never, ever see what’s going on there.

So inside our connect method all we need to do is whenever the system Location Manager sends us a new location we call setValue on ourselves.Then the LiveData knows which are the activity observers, and delivers the data to those observers.if one of the Observer was on the back stack and then becomes visible again, LiveData takes care of sending the latest data back to that observer.

onInactive(), Which means you don’t have any observers, So don’t bother changing your value if it is something that you care about.

 

Related Post

Lifecycle Aware Components

ViewModel

Room Persistence Library

Fragment Tricks

ConstraintLayout 1.1.x

Room Persistence Library

Room Persistence Library

We know that to write a good responsive android app, you need to save data on disk.You need to use SQLite if you want to save big data.We want to get rid of SQLite boilerplate free code.

Room Write boilerplate code for you

Usually, In the database the best practice to put your database access into certain interfaces.You define the interfaces Room provide the implementation.

Full SQLite support

Room Speaks SQL.Most important part of Room is it understands your SQL.So, the Part all those constants. Room actually gives all of this for free.

Compile time validation

Room defined to get compile-time guarantees.Room is going to give you an error at compile time.So it goes out and verifies your query against the schema you have defined, it tells you is something is wrong.

Incentivises best practices

You can basically create any java class.It doesn’t need to be annotated, there’s nothing special about POJO, and tell Room to return It.As long as whatever query it returns.Matches what you want it to return, Room will write the code for you.

Observability is important ?

We want to get notified when the data changes.If you want to do this all you have to do tell it to return a LiveData and it will do it for you.Because it Knows your query, it knows what things affect it.So it can let you know if that query changes.

This is the part where all these architecture components work well together.Room already knows about live data.

So your ViewModel all you would write is the data, from the data is call this query and this all it will do.Whenever that data changes, your UI will get a new update.

Adding Components to your Project

open the build.gradle file of  project  and add the line as shown below:

Open the build.gradle file for your app and add the artifacts that you need as dependencies:

Create Entity

Represents a class that holds a database row. For each entity, a database table is created to hold the items. You must reference the entity class in the Database class. Each field of the entity is persisted in the database unless you annotate it with @Ignore.

room entity

When a class is annotated with @Entity and is referenced in the entities property of a @Database annotation, Room creates a database table for that entity in the database.

Nested objects

You’d like to express a POJO as a cohesive whole in your database logic.In these situations, you can use the @Embedded annotation to represent an object that you’d like to decompose into its subfields within a table. You can then query the embedded fields just as you would for other individual columns.

Our User class can include a field of type Address. To store the composed columns separately in the table, include an Address field in the User class that is annotated with @Embedded, as shown in the following code snippet:

Indices and uniqueness

You might want to index certain fields in the database to speed up your queries. To add indices to an entity, include the indices property within the @Entity annotation.You can enforce this uniqueness property by setting the uniqueproperty of an @Index annotation to true.

Relationships

Room allows you to define Foreign Key constraints between entities.

For example, if there’s another entity called Book, you can define its relationship to the User entity using the @ForeignKey annotation, as shown in the following code snippet:

You can tell SQLite to delete all books for a user if the corresponding instance of User is deleted by including onDelete=CASCADE in the @ForeignKey annotation.

Data Access Objects (DAO)

This component represents a class or interface as a Data Access Object (DAO). DAO are responsible for defining the methods that access the database. When generating the code at compile time, Room creates an implementation of this class.

@Insert

Create a DAO method annotate with @Insert .Room generates an implementation that inserts all parameters into the database in a single transaction.

The following code snippet shows example queries:

It can return a long, which is the new rowId for the inserted item. If the parameter is an array or a collection, it should return long[] or List<Long> .

@Update

It uses a query that matches against the primary key of each entity.

@Delete

Deletes a set of entities, given as parameters, from the database. It uses the primary keys to find the entities to delete.

Delete and Update method can return an int value instead, indicating the number of rows updated in the database.

@Query

It allows you to perform read/write operations on a database. Each @Query method is verified at compile time.

Room also verifies the return value of the query such that if the name of the field in the returned object doesn’t match the corresponding column names in the query response.

Querying multiple tables(JOIN)

Room allows you to write any query, so you can also join tables. Furthermore, if the response is an observable data type, such as Flowable or LiveData, Room watches all tables referenced in the query for invalidation.

The following code snippet shows how to perform a table join to consolidate information between a table containing users who are borrowing books.

Data type converters

You sometimes use a custom data type whose value you would like to store in the database in a single column. To add this kind of support for custom types, you provide a TypeConverter, which converts a custom class to and from a known type that Room can persist.

Create Database

The annotation defines the list of entities, and the class’s content defines the list of data access objects (DAOs) in the database. It is also the main access point for the underlying connection.

The annotated class should be an abstract class that extends RoomDatabase.

class must contain an abstract method that has 0 arguments and returns the class that is annotated with @Dao.

 

java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.

At runtime, you can acquire an instance of it by calling Room.databaseBuilder() or Room.inMemoryDatabaseBuilder().

Download this project from GitHub.

 

Related Post

How to use DateTime datatype in SQLite Using Room

Lifecycle Aware Components

ViewModel

LiveData

Fragment Tricks

ConstraintLayout 1.1.x