Category: Interactivity

Create a Time-Management App – Layout

Create a Time-Management App – Layout

The first thing we start out with in our App, is building the Layout itself. It won’t be the final layout, but a very basic startingpoint for us, to focus our efforts on coding the app itself first. To start off, change the standard ConstraintLayout to a LinearLayout.

Also, make sure that you create an android:orientation tag above the android:layout_width tag, and set it to vertical.

android:orientation="vertical"

The main element is going to be a listView. We want our TimeSpans, such as "Today", "Tomorrow" etc. to stack up on top of each other in the first view.
Add this element to your activity_main.xml file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.rechunk.checkmark.MainActivity">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/listView">
    </ListView>

</LinearLayout>

Make sure to set the layout_width and layout_height to match_parent, so that the listView fills the entire screen. Also, I have it an id of listView. Now, go into your MainActivity.kt file.

What we want to do, is populate our ListView with all the timeSpans we intend to use. For this, we will be using an ArrayAdapter. The ArrayAdapter takes an Array and converts it into listView items. We start by declaring and initializing our array of time spans:

 

var timeSpans: Array<String> = arrayOf("Today", "Tomorrow", "Later this Week", "Sometime Soon")

 

Before we can move on, we have to create an actual view that is able to display each element in the array the way we want. For this, create a new file in the layout folder. I call mine row_layout.

I simply added some very basic and ugly styles to a TextView. It will be enough for now.

 

Okay, go back to MainActivity.kt. We can now create our ListAdapter:

val adapter: ListAdapter = ArrayAdapter<String>(this, R.layout.row_layout, R.id.customTextView, timeSpans)

we declare a ListAdapter, and set it equal to an ArrayAdapter of Strings, as our Array only contains Strings (for now). Then, we pass in the context, which is the current state of the application using this, specify the row_layout we just created, the customTextView inside of the row_layout and finally pass it the timeSpans-Array.

 

Then, we want to find our listView itself and set the adapter:

 

val listView = findViewById(R.id.listView) as ListView
listView.adapter = adapter

 

Finally, we want to be able to detect clicks. This is the code for it, which currently is not Kotlin-Optimized just yet:

listView.setOnItemClickListener(object : AdapterView.OnItemClickListener {
    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {

        
    }
})

Inside of the OnItemClick method, we later want to be able to navigate to the proper view.
Now, just run the program (make sure you set up your emulator or have a physical device connected), and you should see something along those lines:

 

Ugly, but good enough for us to understand how we can make it look good 🙂

AND good enough, for us to be able to start coding the functionality in the next part.

 

Stay tuned 🙂

Five Features That Make Kotlin Awesome

Five Features That Make Kotlin Awesome

  • map-filter

I hope that by now, you are convinced that Kotlin is truly awesome. Here are 7 of my reasons, that make Kotlin unique, powerful and intuitive to work with:

 

1) Underscore Seperator

We read code more often than we type it. Have you ever experienced reading a large integer, and found yourself counting the digits just to see how large it actually is?

var maxInteger: Int = 2147483647

Luckily for us, Kotlin allows us to place underscores between the digits to get a quicker read, without actually affecting the number:

var maxInteger: Int = 2_147_483_647

This gives you a better read by letting you distinguish between smaller and larger numbers more easily without having to count all the digits every time.

 

2) If-Expressions

You might be familiar with the way of initializing variables based on a condition in other languages. For example, in C#, you might do something like this:

bool isEighteen = (age >= 18) ? true : false

This is obvious enough if you know what it means, especially in this context. But when I was starting out, I had no clue what was going on reading more complicated expressions. Kotlin makes it more understandable by incorporating the if-keyword itself.

bool isEighten = if (age >= 18) true else false

You can also do things, besides assigning based on the condition:

bool isEighten = if (age >= 18) {

print("You are old enough to drive a car!)
true

} else {

print("You are still very young!)
false

}

 

3) Null-Safety

This is the features  you have most likely already heard of. Compared to Java for example, Kotlin prevents us from assigning null to a variable if we don’t explifitly allow it to accept null.

var cantBeNull: Boolean = null // gives us an error

We have to use a ? to make it valid.

var cantBeNull: Boolean? = null // compiles just fine

This prevents us from NullSafetyErrors at runtime.

 

4) Return When

This is a feature introducted to clean up our code a little bit. When you could return multiple values, based of many conditions instead of typing this:

fun getCommentBasedOnAge (age: Int){
   when(age) {
     when (age){
        1 -> return "Hey Baby"
        2 -> return "You are getting older..."
        3 -> return "Already 3 years old!"
        4 -> return "Two more years until you go to school"
        5 -> return "The last year before school..."
        6 -> return "You are finally in first grade!"
        else -> return "You are too old for this..."    
     }    
   }
}

 

You can simplify it by putting only one return keyword before the when statement itself:

fun getCommentBasedOnAge (age: Int){
   return when(age) {
     when (age){
        1 -> "Hey Baby"
        2 -> "You are getting older..."
        3 -> "Already 3 years old!"
        4 -> "Two more years until you go to school"
        5 -> "The last year before school..."
        6 -> "You are finally in first grade!"
        else -> "You are too old for this..."    
     }    
   }
}

We just removed six unneccessary return keywords that did not add anything to our code.

 

5) Map-Filter

 

 

Map-Filter inside of Kotlin has a pretty neat way of functioning. They work with lamba expressions, which is not particularly unique to Kotlin. But as opposted to other languages, you can use the it keyword to describe all items you want to manipulate. Here is an example of it in action:

names
.sortedBy { it }

This simply sorts all the elements inside of the “names” alphabetically. You can add more actions by putting them underneath each other:

names
    var names = listOf("Bob", "Robbinson", "OG", "John")
    names = names
            .sortedBy { it }
            .filter { it.length >= 3 }
       
    
    names.forEach { n -> println(n) }

This example first sorts the names, and then removes all names that are not at least three characters long. Afterwards, we print out our list.

There are obviously many more awesome features you will find in Kotlin. For this post, I chose these five as they are very valuable in many situations you will encounter.

I hope you enjoyed them and have fun trying out all other features you can find.

Cheers, Gabriele

The Core Syntax of Kotlin – Part 1

The Core Syntax of Kotlin – Part 1

If you are new to programming, this series may not be the best entry point. In this case, check out my youtube channel, where I am starting a series covering the core fundamentals of programming using Kotlin. This series however, is designed for programmers with the basic knowledge of the core principles of programming, which apply to most programming languages. Make sure to download IntelliJ if you haven’t already and create a new file called “main.kt”.

This is the entry point of our application:

fun main(args: Array){

}

Inside of Kotlin, we declare functions using the fun keyword. Printing out information is easy as well:

fun main(args: Array){

   println("Followed by new line")
   print("Not Followed by new line")
}

Let’s now get to declaring variables:

fun main(args: Array){

   var age: Int = 10
   age++
   val yearOfBirth = 1990
   // Changing yearOfBirth would give an error
}

The major datatypes we use are:

– String
– Int
– Double
– Float
– Char
– Boolean

There are others like Short, Byte or Long which you’ll be able to use as well.

We use the var keyword, followed up by a name, a : and the appropriate datatype to declare variables. We then initialize them with the appropriate value.

Note: Inside of Kotlin, specifying the datatype is optional. The compiler will be able to figure it out on it’s own.

With the val keyword we define constants, which are not allowed to change at runtime. For example, it would make sense to define PI inside of a constant.

 

This is how we can define an array of variables:

fun main(args: Array){

   var allNames = arrayOf("Tim", "Bob", "Rob", "Kevin")
}

using the arrayOf() function allows you to declare your array. You can use a similar function, called listOf(), to declare lists.

Printing out all elements in our array is easy as well:

fun main(args: Array){

   var allNames = arrayOf("Tim", "Bob", "Rob", "Kevin")

   for (name in allNames){
      println(name)
   }
}

Similar to languages like python, we specify the name we want to use for the current elements and use the in keyword.
However, inside of Kotlin there is no way to use our well known for loop for printing out numbers until a specific value like in this this: (int i = 0; i < 10; i++). Instead, we use ranges.

fun main(args: Array){

   for (num in 1..10){
       print(num)
   }
}

You can also define your range in a variable if you prefer it:

fun main(args: Array){

   val oneToTen = 1..10

   for (num in oneToTen){
       print(num)
   }
}

There are also multiple ways of reversing the order:

1.

fun main(args: Array){

   val oneToTen = 1..10

   for (num in oneToTen.reversed()){
       print(num)
   }
}

2.

fun main(args: Array){

   val tenToOne = 10.downTo(1)

   for (num in tenToOne){
       print(num)
   }
}

You can either call the reversed() function, or simply use the downTo() function when initializing your range.

If-Else statements are basically the same as in most programming languages:

fun main(args: Array){

   val age = 18
   val isWithParents = true

   if (age >= 18){
      println("Welcome to this club!")
   }
   else if (age < 18 && !isWithParents){
      println("Sorry, you can't enter this club!")
   }
   else if (age < 18 && isWithParents){
      println("Welcome to this club!")
   }
}

These are the most basics of the basics you will find. In the next post, we will continue this series and add on our syntax scanning. We will be covering things like when, which is what you might know as switch, functions, classes and more.

See you on the next post.

Create Android Apps with Kotlin – Coding the Functionality

Create Android Apps with Kotlin – Coding the Functionality

Finally comes, what I would consider, the fun part of creating Apps: Coding the logic.

But obviously, we want to be able to access the individual elements on our page within our code. To do so, let’s change the ID of our components inside of the text view of activity_main.xml:

 

 

Make sure to choose descriptive, meaningful names. Now, we are good to go. Change back to your MainAcitivity.kt file. We start everything inside of the onCreate method. As soon as the user clicks on the button, we want to make a calculation. To detect clicks, we’ll add an onClickListener to our button:

findViewById(R.id.resultsButton).setOnClickListener {

}

For now, we’ll still use findViewById, just for simplicity. Calling this function, requires us to pass the ID of the element we want to access. I called my button resultsButton, and therefor pass R.id.resultsButton as the parameter (accept the R for now).

Next up, we need to access our edit fields in a similar way:

findViewById(R.id.resultsButton).setOnClickListener {

   val moneyField: EditText = findViewById(R.id.moneyField) as EditText
   val moneyGoal: Float = getNumberFromTextField(moneyField)

   val salaryField: EditText = findViewById(R.id.salaryField) as EditText
   val salary: Float = getNumberFromTextField(salaryField)

   val increaseField: EditText = findViewById(R.id.increaseField) as EditText
   val increase: Float = getNumberFromTextField(increaseField)
}

Again, we use the findViewById() function casting the result as the Object we want to have, which, in this case, is a EditText. For accessing our values, I call a method named getNumberFromTextField(), which we have not created, yet. I do this to try to seperate usage from implementation. This is what the function looks like:

fun getNumberFromTextField(field: EditText): Float {
        return field.text.toString().toFloat()
}

it simply accesses the text property of the EditText we pass it, converts the result into a string and then into a float (And returns it). At this point, we managed to get the user input after the user clicks on the button. The last thing we do inside of setOnClickListener is call a function, passing it the parameters we just received:

calculateAndDisplayTimeUntilMoneyGoal(moneyGoal, salary, increase)

Again, we need to implement it.

fun calculateAndDisplayTimeUntilMoneyGoal(goal: Float, salary: Float, increaseInPercent: Float){
        var moneyEarned: Float = 0f
        var currentSalary = salary
        var months: Int = 0
        var yearsPassed: Int = 0

}

The first thing I do inside of it is declare some variables. Note that I declared the currentSalary variable, because we need to change it at runtime and using the variable we passed to the function as it is makes it impossible for us to change the salary, because what we pass is a constant (val).

Let’s start coding the functionality. We want to calculate how long it takes to achieve the goal of x amount of money. Therefor, we are done as soon as we have equal as much or even more money than we wanted to have, which is why I use the following while loop:

fun calculateAndDisplayTimeUntilMoneyGoal(goal: Float, salary: Float, increaseInPercent: Float){
        var moneyEarned: Float = 0f
        var currentSalary = salary
        var months: Int = 0
        var yearsPassed: Int = 0

        while (moneyEarned < goal){
            
        }
}

Let’s now focus only on the while loop. Each iteration, one month passes by, therefor we get our salary. I also keep track of the months by incrementing the variable.

while (moneyEarned < goal){
             moneyEarned += currentSalary
             months++

}

Every year, our salary increases. So we now have to check, if one year is over this month:

while (moneyEarned < goal){
            moneyEarned += currentSalary
            months++

            if (oneYearPassed(months)){
                
            }
 }

I use a one-line function for better readability called oneYearPassed, which we pass in integer.

fun oneYearPassed(months: Int): Boolean = (months == 12)

If the function returns true, I increase the salary, reset the month counter and increment the year counter:

while (moneyEarned < goal){
            moneyEarned += currentSalary
            months++

            if (oneYearPassed(months)){
                currentSalary += increaseSalary(currentSalary, increaseInPercent)
                months = 0
                yearsPassed++
            }
}

This is how the increaseSalary function looks:

fun increaseSalary(currentSalary: Float, increaseInPercent: Float): Float {
        return (currentSalary / 100) * increaseInPercent
}

It returns the increase in salary we want to add to our current salary. Our while loop is done!
The last thing we need to do is display the information to our user:

fun calculateAndDisplayTimeUntilMoneyGoal(goal: Float, salary: Float, increaseInPercent: Float){
        var moneyEarned: Float = 0f
        var currentSalary = salary
        var months: Int = 0
        var yearsPassed: Int = 0

        while (moneyEarned < goal){
            moneyEarned += currentSalary
            months++

            if (oneYearPassed(months)){
                currentSalary += increaseSalary(currentSalary, increaseInPercent)
                months = 0
                yearsPassed++
            }
        }

        val resultsString = "After $yearsPassed years and $months months you will have earned $moneyEarned!"
        (findViewById(R.id.displayText) as TextView).text = resultsString
}

And voila! We finished our application. It’s by no means perfect, and could maybe use a bit of rework, but should give you an impression on what coding an app with kotlin looks like.
Run your application and test it out with your phone or virtual device.

I hope to see you back in the next post, where we will be looking at a more advanced example.

Peace.

Create Android Apps with Kotlin – Basics of Layout

Create Android Apps with Kotlin – Basics of Layout

The most important part of any app is the layout. Because, what do we do without it? Our code won’t do anything if we don’t allow the user to call it. Let’s learn the basics of it by building a small application. We want to create an application that calculates how long we’ll have to keep working in our job to achieve a certain amount of money, keeping in mind the increase in salary every month.

So, first things first, change the Layout of your application to a LinearLayout by changing the standard layout of your activity_main.xml and add the android:orientation tag:

 

 

Doing so, our widgets will stack up on top of each other. This is an example with buttons that I just dragged into the window:

 

 

You might wonder why my background is grey. Go into your AndroidManifest.xml file inside of app -> src -> main and change the android:theme tag to this:

 

 android:theme="@style/Theme.AppCompat.NoActionBar">

 

Add a new color tag inside of colors.xml in app -> src -> main -> res -> values:

 

<color name="darkGrey">#2C2C2C</color>

 

Now, all that is left to do is alter the android:background tag inside of your activity_main.xml text file:

 

 

But back to our application concept:

On the top left of the Design window, click on “Text” and drag three Plain Text Widgets into the Editor. The first one lets the user enter their goal of money, the second one their current salary, and the third one the increase in salary each year in %. Make sure to replace the hint in the properties window with correspondant text (hard-coding is generally bad practise, but good enough for this very basic example where we don’t need to translate our text into other languages) and remove the “Name” from the text property, to make sure the textview is empty at the beginning.

 

 

Next, we add a Button and a TextView, in order to display the result of our calculation. Additionaly, I change the alignment of the text to center.

 

 

This look cluttered, doesn’t it? Everything truncates to the top and there is a whole bunch of white space on the bottom for no reason. Let’s go into the margin property and add some marginTop to each widget. This will add more space on the top of each Widget:

 

This is a bit better, I guess.

But what now? Now should come the part where we actually start coding. The thing is that we haven’t touched on any Kotlin code up until this point. I don’t want to leave you in case you are not familiar with Kotlin, yet. If you are new to Kotlin or programming, make sure to check out my video series on youtube about the basics of the language.

If you are really motivated, try finishing it on your own! It will be awesome practise. You can compare your solution to the problem with mine as soon as it’s there.

Until then, stay tuned for the upcoming series and our coding of this multi-reward winning mobile android application.

 

Cheers.