Kotlin RecyclerView

In this post we will write in Kotlin a very simple example for RecylcerView.

First, you can search for RecyclerView in the view search box. Drag and drop the RecyclerView below ConstraintLayout and you will be prompt to import in app – build.gradle.

activity_main.xml

list_item.xml

 

MyCustomAdapter.kt

 

MainActivity.kt

 

Kotlin ListView with ViewHolder

In this post we will create a ListView with ViewHolder adapter but we will write the code in Kotlin.

For creating xml files for ListView and list items, follow the steps from this post.

Next, you have to create a new Kotlin class for the adapter. Name the new created file MyCustomAdapter

MyCustomAdapter.kt

What’s different in this adapter written in Kotlin compared to the one in Java is that we had to create rowView variable in order to be able to inflate the list_item layout to the view. In Kotlin if we try to inflate the layout directly to the view: View? attribute we will get an error “Val cannot be reassigned”.

MainActivity.kt

 

 

Kotlin Common Questions

1. Where should we keep constants in Kotlin?

  • if you need constants to be accessed globally use const as top-level properties (not inside a class).

In order to do this create a Kotlin file named Constants.kt. The file would look like this:

This way you will be able to access the constants from anywhere within the app just by typing the constant name (in Kotlin code). In Java code you will need to write ConstantsKt.MY_APP_ID.

  • if you have constants that are specific to a scope, like Employee for example, create a companion object

And this is how you use the constants.

2. What do ?, ?., ?: and !! mean?

3. How to make casts in Kotlin?

4. How to use Parcelable in Kotlin?

5. How to create a Singleton in Kotlin?

6. How to create a List in Kotlin?

List

List

  • Create a List in Kotlin

Important!

In Kotlin, lists are immutable by default (you can’t add or remove elements after the list is created). If you need to make a list mutable, you can do this by using mutableListOf

OR

by creating an ArrayList.

BUT it should be just a temporary list. It is not recommended to keep mutable lists for too long.

  • Mixed types

When you create a list in Kotlin, you can add mixed types to the same list:

  • listOfNotNull() Function

The output of the above code will be this:

Notice that null values are ignored.

  • Empty lists

There are 2 ways to create empty lists. They do the same thing, so it’s up to you which way you prefer.

OR

emptyList<String>() returns an Immutable empty list.

7. How to create a SET in Kotlin?

  • Create a Set in Kotlin

  • Create a HashSet

  • Create a SortedSet (TreeSet in Java)

  • Create a LinkedSet (LinkedHashSet in Java)

 

8. How to create a Map in Kotlin?

  • Create a Map

  •  How to iterate a Map?

HashMap, LinkedMap (LinkedHashMap in Java) and SortedMap are all mutable.

9. What collection methods are useful?

any()

Returns true if collection has at least one element.

any(predicate: (T) -> Boolean

Returns true if at least one element matches the given predicate.

 

asReversed()

Returns a reversed read-only view of the original List.

Output

 

Smart home (IoT) – the beginnings

Intro

Since I am a fan of DYI and love gadgets(and IoT), I started to play with a Raspberry Pi and ESP8266 for a while. I had some failing ideas like automating my curtains, after long plans and setup, I abandoned the idea because I couldn’t see a way to make it look nice with the Raspberry Pi board. But now I finally managed to wrap up something that I use and would like to share with others.

It is about automating my kitchen led band by adding the ability to switch it off/on using and Android phone and a physical button(because you don’t have the phone on you in the house always 😛 ).

The first IoT “Thing”

I would like to call this setup a “thing” from the IoT (Internet of Things) because I would like to work more on it and finally make it behave just like a real IoT thing.

At this moment we can name it “Smart switch” because it can connect to a Wifi router and switch a relay ON and OFF, and it also has the fancy button. I hope in the near future to smarten it more and more. Currently as I said, with the relay, I am switching my kitchen’s led band ON and OFF but one can use it to switch any outlet ON/OFF or other equipment that makes sense.

Please note that I don’t take any responsibility for any damages that you might encounter while doing this, I am still at the early beginning of my IoT journey.

Ok, so here is what you can see in this article:

  • Code for the Android application
  • Arduino code for the NodeMCU ESP8266 board
  • How to wire the hardware components on the NodeMCU ESP8266 board
What can the NodeMCU ESP8266(custom built) do:
  • connect to a WPS enabled router
  • be discoverable on the network using the mDNS protocol
  • get input from a button
  • create a web server that manages the relay
  • controls a relay
What can the Android app do:
  • search for the NodeMCU ESP8266 module on the network and get the IP address
  • check the relay’s current “status” (ON/OFF)
  • switch the relay ON/OFF
Hardware components that I am using:
  • android phone 🙂
  • NodeMCU v2 – Lua ESP8266 board
  • Solid state relay that can operate up to 340VAC and can be switched with a low of 3VDC (this one)

The high level schema of the system can be checked below (Schema 1).

NodeMCU smart relay schema
Schema 1 – NodeMCU ESP8266 smart relay schema

 

The wiring of the hardware components(button and the relay) on the NodeMCU ESP8266 board can be found in Schema 2 below.

Schema 2 – ESP8266 and relay wiring

 

Note that the wiring diagram does not position the lines to the real GPIO pins, instead I noted the exact GPIO pins so the position will be different than in the diagram. D1 corresponds to GPIO5, D2 to GPIO4 so in the Arduino code you will find them referenced as 5 and 4. Also, the relay I am using emits a charge of a few volts back to the board. That makes the button press detection to trigger false positives. There is a way to outcome that hardware wise but I don’t know exactly the component that I should use in order to avoid the charge and so I made some hacks in the Arduino code. I will get back with updates when I will find out how to fix it properly. If you know how, please let me know.

Below you can find the NodeMCU ESP8266 pins layout. You can find out more about that here.

ESP8266 NodeMCU pins
ESP8266 NodeMCU pins

 

Below you can also see a small sample of how my setup looks like (I know, it doesn’t look nice, I bought some stuff to box it 🙂 ).

IoT with ESP8266 with relay and a power source for a led band
ESP8266 with relay and a power source for a led band

 

A few details…

The led band is powered by a transformer that outputs 24V from 220VAC. What I’ve done was to put the relay in front of the 220VAC of the source and switch it off and on whenever I need it to. The ESP8266 sends a 3VDC power to the relay and in that moment the relay turns ON and the led band lights up.

I bought a solid state relay because those are responding faster and have longer life than the other one. Please share your thoughts if this doesn’t make sense for you. The whole project(hardware) cost me about 40 dollars (max) and it is not built with cheap components so one could get it below that(depending on the region and trading skills :)) ).

The code for both the Arduino and Android projects can be found on my Github account HERE. Please let me know if you have issues or you have better ideas and feel free to contribute.

At last

I would like to end with a list of items that I want to address in the future and also some util links.

Future improvements:
  • fix the relay leak hardware wise and not in code
  • implement a well known and widely used IoT things protocol so that other smart home servers could talk with my “smart relay”
  • implement a better wifi connection and discovery mechanism (remember the connection after a restart…)
  • refactor the android app to abstract the “Thing” and add support for future things
  • integrate with IFTTT
  • integrate with Google Assistant
Util links:

Thank you for reading all this long post, please let me know if you managed to setup this and also your opinion/experience with IoT.

Meanwhile I managed to link the ESP8266 to my Google Home assistant speaker using IFTTT using a web hook for now. See the video below.

 

And a short demo with the beast 🙂

 

Kotlin – for, while, if, when

Control flow: for, while, if, when

This post is for beginners who want to start learning Kotlin language and already know Java. We will show simple examples of for, while, if, when in both languages, in parallel, for an easier understanding. We will use Log.e in order to print string messages, as from our point of view, is easier to read them in the Logcat.

1. for loop

Enhanced For-Loop

Java

  • inline

  • using block

Kotlin

  • inline

Notice that in Kotlin we used a “$” symbol in order to obtain the value of name variable. This is called a template expression.

  • using block

Index-based loop

Java

Kotlin

Notice that here, we used beside “$” symbol, curly braces “{“. This was necessary because names[i] is an expression.

withIndex or Ranges loop

Java

Kotlin

OR using Ranges (Kotlin)

 

2. while loop

The while loop in Kotlin is the same as the while loop in Java.

Both Java and Kotlin

 

3. if expression

Traditional usage

Java

Kotlin

As an expression (inline if)

Java

Kotlin

In both Java and Kotlin, if we use inline if, the “else” branch is required.

As an expression with blocks

Java 

NONE

Kotlin

  • 1 statement

The output for the above code will be:

  • 2 statements or more

The output of the above code is this:

What happens in this case? Well, a is indeed lower than b, so the code from the if branch will be executed. First, it will log the “a is min” message, and then a value will be assigned to “message” variable and the latest Log.e will log the message “min = 1” because a = 1.

As the official documentation states: ” if branches can be blocks, and the last expression is the value of a block”.

4. when expression

when expression in Kotlin is the equivalent of switch in Java.

General form

Java

Kotlin

The output is:

Many cases that should be handled in the same way

Java

Kotlin

The output is:

Arbitrary expressions (not only constants)

Java

In Java we can’t use arbitrary expressions. Constant expressions are required.

Kotlin

Check a value for being in or !in a range or a collection

Java

NONE

Kotlin

The output is this:

 

Check that a value is or !is of a particular type

Java

NONE

Kotlin

Output is:

Notice that in this scenario we assigned the value of when expression directly to the isInt function (method). This is one of the shorter ways of writing a function.

Replacement for an ifelse if chain

Java

NONE

Kotlin

The output is:

Note that in this scenario, when expression is followed directly by a curly brace “{“.

 

 

Android Show HTML Bulleted List from strings.xml

If you search on the internet about how to show a bulleted list from strings.xml using HTML tags, most of the answers will say that you should use a WebView, or to use the bullet symbol directly, or other alternatives. And on some posts I even read that you can’t use <li> tag from HTML because it is not recognized in Android. This is totally untrue. Here, in this post you can see all the HTML tags which are supported and which are NOT supported. I tried them all 🙂

Below I will show you how I used <li> tag in order to show a bulleted list from strings.xml.

strings.xml

activity_main.xml

Activity

 

And below is the result 🙂

As you can see, is pretty easy to show a bulleted list if you need to show it on a TextView. So there’s no need to refactor your code to use WebView or other alternatives. Of course, if you don’t like this approach, you can use the others. I don’t want to imply this the correct and only way to show bullets. But I wanted to write this post, because I didn’t find this approach anywhere else and maybe someone will need it, or like it more than the other ones :P.

Please let me know if you find this post useful by writing a comment or rating it. Also don’t forget to share it if you liked it 😉

Android Activity launchMode

In Android you can specify activity launchMode. You can do this either from AndroidManifest.xml file, either using intents with flags. Some of the flags produce the same effects like those from AndroidManifest.xml, but there are some flags that can be declared only with intents and also there are flags that can be declared only inside AndroidManifest.xml. In this tutorial we will talk only about those from manifest.

launchMode

There are 4 types of launchMode:

standard

Standard is the default launch mode used by the system. If you don’t set any launch mode to your activity, it will use the standard mode by default.

singleTop

We have the following scenarios:

We have 4 activities: A, B, C and D

Scenario 1

  • D activity has launchMode declared in AndroidManifest.xml as singleTop, the other 3 activities have standard

  • the navigation of the activities is: A -> B -> C -> D. From D activity, we start activity D again.

Current Stack:

Question: What happens when we tap the back key?

Answer: The stack remains the same and the navigation is as follows: D -> C -> B -> A

Use case: Search function

Scenario 2

  • activity has launchMode=”singleTop”, the other 3 activities have standard
  • the navigation of the activities is: A -> B -> C -> D. From D activity, we start activity B.

Current Stack:

Question: What happens when we tap the back key in this scenario?

Answer: A new instance of B activity was added to the stack. The navigation is as follows: B -> D -> C -> B -> A

Conclusion

As you can see, singleTop flag, prevents instantiating a new existing activity only if the activity containing this flag, is the last one (at the top of the stack) like in Scenario 1.

singleTask

What is a task?

  • a task is a collection of activities
  • tasks can be seen in the Recent Apps from your device
  • an app can have multiple tasks
  • an activity declared with launch mode as singleTask can have only one instance in the system (singleton).
  • even though a new task is created, the Back button still returns the user to the previous activity

Use case

An example would be a web browser activity which should always open in its own task. This means that if you open a web browser from your app, it will open in a separate task from your app.

How does it work?

Let’s take an example. We open an app that was not opened recently, so the system creates a new task for this app, let’s say task1. You navigate through the app, and then press the Home button. At this point, the app goes in background, and all the activities are stopped, not destroyed, stopped. This means that the back stack of these activities remains intact. Now, if you open another app, with its own task (task2), and then put this one in the background and resume the first app (task1), you will see that you can pick up where you left off. The activity at the top of the stack will resume, while the other activities from the task remained intact. This means that if you press the Back button you will navigate back through the activities.

Create new task from same app

Scenario 1

We will use the same activities as earlier in this post (A, B, C and D) with the same navigation just that we will open C activity in a new task. The code is this:

Important: Notice that we have to declare taskAffinity in order to open activity in a new task like the documentation states. Without taskAffinity, it will open in the same task (though the behavior of back stack might be different . See Scenario 4)

You can also see the task recording of the activities by using dumpsys activity command in the terminal from Android Studio (no logs or anything in the code):

And this what the above command will show us:

As you can see, A and B activities are in task t267 while C and D are in a new separate task t268. C is the root activity for the new task.

Scenario 2

In this scenario, we will let the C activity to be the only one declared with launchMode as singleTask, but we will change the navigation through activities. This is the order:

A -> B -> C -> D -> B -> C

As you can see above, from D activity we will try to open B activity and then again. Let’s see what happens.

A -> B -> C -> D -> B 

At this point, we have 2 instances of B activity. One in task t305 and a new one in task t306. Let’s see what happens next.

A -> B -> C -> D -> B -> C

“Oh, well, what happened here?”, you might wonder. This happened:

  • C activity is declared as singleTask. This means that only one instance of this activity can exist in the system. So, the system brought the existing C activity in front of B from task t305.
  • in the process of bringing C activity in front of B, the system destroyed the above activities from task t306 (D and B from task t306)

Scenario 3

Let’s suppose that:

  • C and D activities are already in the background
  • D activity is declared with singleTask.
  • A and B activities are in a separate task.

What happens if we open D activity from B activity? See the image below:

As you can see, starting D activity declared as singleTask which already exists in background, from B activity, will move the whole stack of activities from D‘s task in front of B. Thus the back stack of the activities is now A – B- C – D.

Scenario 4

In this scenario, we will test what happens when we declare activity as singleTask, but without taskAffinity.

The navigation through activities is this:

A -> B -> C -> D

Notice that activity, even though is declared with launchMode=”singleTask” it seems to be in the same task t340 as the other activities. This means that using singleTask will NOT always put the activity in a new task at the root as the documentation states. BUT declaring singleTask for is not completely redundant. Look what happens next, when we want to open B again from activity:

A -> B -> C -> D -> B

and activities have been destroyed even if all activities were in the same task. This happens only if we open again an activity declared as singleTask, in our scenario B. If we had opened A activity, it would have been added on top of D.

Scenario 5

Now, let’s see what happens if we declare singleTask for activity D, without taskAffinity:

If we run the app we will notice that D activity is not in the same task as activity C, but it is in the same task as A and B activities.

singleInstance

This launch mode is the same as singleTask, except that an activity declared as singleInstance is always in a separate task and it is the only activity in that task. Any activities opened from this one, open in a separate task.

We will take an example.  The navigation through activities is this:

A -> B -> C -> D

C activity is declared singleInstance. Below is the stack.

As you can see, C activity is alone in a separate task, while A, B, D are in the same task.

taskAffinity

An activity can be set to prefer being in a certain task by using affinity. By default, all activities belong in the same task because they have an affinity for each other.

taskAffinity can be used in 2 cases:

  • when using launchMode singleTask
  • when using allowTaskReparenting

We will discuss only the first case in this tutorial.

taskAffinity with singleTask

In this case, the system looks for launching the activity in a new task. Often, it’a a new one, but it doesn’t always have to be a new one.  If there’s already an existing task with the same affinity as the new activity, the activity is launched into that task. Otherwise, it begins a new task.

  • the taskAffinity attribute takes a string as value which has to be declare with “.”, but has to be different from the package name of the app, because that is the default value of the system.
  • If you put an empty string “” as vaslue, will mean that that activity will not have an affinity for any task.
  • if you don’t add taskAffinity to your activity, it will inherit the affinity set for the application

Android Add Game Leaderboard

In order to display leaderboards from your game you will have to set up your project and to be signed in. Below you will learn how to do this.

Project Setup

  1. Download the Android samples from https://github.com/playgameservices/android-basic-samples
  2. Import BaseGameUtils into your project as module
  •  Go to the directory where you downloaded android-basic-samples and select libraries -> BaseGameUtils

  • If you get the below error:

 

 

Tap on the link and let the ide install missing platform.

  • You might get another error:

Tap on this link also and then go build.gradle from BaseGameUtils.

Change build.tools and library versions to the latest ones and sync the project. At the time of this tutorial, the current versions are 3.0.0, 27.0.0 and 11.4.2

3. Add to your app build.gradle file compile project (‘:BaseGameUtils’)

 

5. Add ids.xml to res – values directory

You will learn further in this tutorial how to obtain these 2 ids.

6. Add meta-data code inside <application> tag from AndroidManifest.xml

How to get the app_id?

In order to get the app_id and be able to use Google Play games services, you need to:

  • set up the game in the Google Play Console
  • generate an OAuth 2.0 client ID for your Android app.

Below are the steps about how to do this:

1. Add new game in Google Play Console

2. Game Set Up

3.  Go to Linked Apps

4.  Select Android platform

5. Set package name (of your app)

Don’t forget that you have to copy-paste here your app package name. After that, click on the Save and Continue button.

6. Authorize your app now

7. Copy-paste your app SHA1 fingerprint

In order to obtain your SHA1 fingerprint follow the steps from this post.

8. Obtain Application Id

In the screenshot is our application id. You will have to copy yours and then paste it in the ids.xml file from your project.

9. Create your Leaderboard

10. Save Leaderboard

11. Copy Leaderboard id

Copy your leaderboard id and paste it in ids.xml file.

MainActivity class

We just used BaseGameActivity class from BaseGameUtils module. It is an example class that  akes care of setting up the API client object and managing its lifecycle.

IMPORTANT: If your app is unpublished and you haven’t added a test account, you will have to do this.  See the steps here.

Now you should be able to display your leaderboard. 🙂

You can also check the android developers documentation.

Android ViewPager Tutorial

In Android, if you need to swipe from right to left or vice-versa in order to see different data, you can use a ViewPager. In order to use it, you have to implement a PagerAdapter which will generate the pages that the view shows.

ViewPager’s adapters

We can use one of the 3 adapters provided:

  • PagerAdapter:
    • it is the base class for a ViewPager adapter
    • used when you need to display only views
  • FragmentPagerAdapter:
    • extends PagerAdapter
    • represents each page as a Fragment
    • each page is persistently kept in the fragment manager as long as the user can return to the page, but the view hierarchy can be destroyed when not visible
    • mostly used for static pages like tabs
  • FragmentStatePagerAdapter:
    • extends PagerAdapter
    • represents each page as a Fragment
    • handles saving and restoring of a Fragments’s state
    • mostly used for a large number of pages

When an adapter loads a page, it creates the adjacent pages also. This means that for position 0, it will also load the next page from position 1. And for position 1, it will load the pages from positions 0 and 2, and so on.

Fun fact: even though you can set a click listener or a longClick listener on a viewPager, they won’t work. ViewPager does NOT consume click events. You will have to set the click event on your view in instantiateItem() method.

PagerAdapter

First, we will see an example of a ViewPager that uses a PagerAdapter, this means that we will have to display only some views (in our case, some images :P)

activity_main.xml

view_pager_item.xml

MainActivity.java

As you can see, when using the base adapter, we have to implement the following methods at minimum:

  • instantiateItem(ViewGroup, int): in this method we have to inflate the layout which which will represent a page for the given position.
  • destroyItem(ViewGroup, int, Object): in this method we have to write the code that removes a page from its container for the given position. This method is called while the user navigates through pages. For example if the current position is 0 and the user navigates to the next page, which will be on position 1, at this point, the method is not called. But, when the user goes again to a next page, position 2, at this point, the page from position 0 will be removed. And from now on, whenever the user swipes to a next page the method will be called for the next positions, 1, 2 and so on.
  • getCount(): here we have to provide the number of pages that the viewPager will have to display. In our case, the size of list containing our images which is 3 🙂
  • isViewFromObject(View, Object): it is required for a PagerAdapter in order for it to function properly. It checks if Object (the one returned by instantiateItem(ViewGroup, int)) is the same with View.

FragmentPagerAdapter and FragmentStatePagerAdapter

In order to implement any of these 2 adapters you will have to implement just 2 methods to have a working adapter:

  • getCount()
  • getItem(int)

Of course, you can also implement methods from PagerAdapter also if you need to.

In the following example, we will use the same example as above, but using a FragmentStatePager adapter. The example is available for a FragmentPagerAdapter too, as both adapters have to implement same methods.

view_pager_item.xml and activity_main.xml will remain the same. What changes is MainActivity.java class and we have to create a new java class (a fragment), named MyFragment.java.

MyFragment.java

MainActivity.java

FragmentStatePagerAdapter vs FragmentPagerAdapter

What is the difference between these 2 adapters? Well is the way they handle the life of pages. The first will destroy and recreate the pages if we implement getItemPosition() POSITION_NONE. But the latter, will not destroy them, but it will attach and detach them which makes it perfect to use for fragments that are permanent.

Fun fact: notifyDataSetChanged() doesn’t work by itself on a viewPager. It has to be used together with

The above method is triggered by notifyDataSetChanged().