Tag: Android Apps

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.

 

Create Android Apps with Kotlin – Structure

Create Android Apps with Kotlin – Structure

I assume you have Android Studio already installed. If not, head over to the official android website, download it and follow the procedure. As soon as you create a new project, set the name of it and click next. You can skip the next window and click on Finish.

If you have never seen Android Studio before, it will look intimidating. But before we start, let’s actually enable Kotlin support!

Go to File -> Settings and now click on Install Jetbrains plugin…

 

 

In the search which will appear on the top, search for Kotlin and click install.

Now, go to Tools in your toolbar, go down to Kotlin, and click on Configure Kotlin in Project

 

Your settings should be okay, just make sure you’re using the latest version of Kotlin and click on Okay. If you see a yellow bar popping up on top of your Editor, go to the right and click on Sync Now. The final step is to click on Code -> Convert Java to Kotlin File.

Congratulations, everything worked fine. I hope so.

 

But obviously, we want to be able to see what we are building on an actual device! In case you have an Android device, just plug it into your computer, wait a second and then you’re able to click the green play button on top of Android Studio.

 

 

In case you don’t have an Android Phone to your disposal, go to Tools -> Android -> AVD Manager and Create a Virtual Device by clicking on the bottom left.

 

Okay, we’re good to go now!

 

The first thing you’ll see some code. (If not, click on the tab called “MainActivity.kt”).

 

 

The onCreate function is called as soon as we start the application. The highlighted line of code is responsible for bootstraping your view. It sets our activity_main.xml file as the current view.

By clicking on activity_main.xml right next to MainActivity.kt, you’ll be able to take a look at this window:

 

 

this is the design represantation of our file. You see a screen, a palette with availabe widgets and layouts on the top left and a wireframe represantation on the right of the phone. Click on the “Text” on the very bottom left.

 

 

What you see now is the actual xml file.

Note: The Design Window is just a visual represantation of the actual xml file and will convert any change you do manually into xml code.

which means, that we can switch between the Design and Text window, while I would still recommend doing the majority of your work inside of the Text window, as it gives you a clearer understanding of what is actually going on.

 

At this point, you have a very brief understanding of what is going on in our application, although we haven’t written any code yet. On the next part of this series we will tackle writing a very basic any minimalistic app and walk you through how to access widgets in code with Kotlin, handling onClick events, sending little toast messages to your users and more.

I hope you stay tuned for the next part.

 

Cheers.

Create Android Apps with Kotlin – Introduction

Create Android Apps with Kotlin – Introduction

Recently, Google announced Kotlin to be fully supported for Android Development. This is good news for us Android Developers! A modern alternative to Java with awesome, new features added to our developer bundle. On the other hand this means, that we somehow need to shift our focus to using Kotlin inside of Android Studio. Companies like Uber are already integrating it into their workflow, which is a hint that Kotlin will be big for sure.

 

And let’s be honest, most of us want something fresh, don’t we?

 

In the following few parts of this series, I will go through the full process of developing Android Apps in Kotlin. It doesn’t matter if you are new to Android Studio or App Development in general, but as always, experice will help you.

In case you already have developed native Apps for Android, you should be familiar with Android Studio. But if you are not, that is completely fine as well. Because the next post, will soly focus on Android Studio and explaining all the basics you need to know about it. Following it up, we’ll create a very simple layout and backend code with the aid of Kotlin.

 

It seems as if the industry is shifting towards Kotlin, and learning something new has never harmed somebody.

 

And for sure Kotlin is a huge improvement when it comes to handling null. But more about it in the upcoming posts. Apart from teaching you the language and it’s awesome features itself, at the end, the most important thing is being able to serve your customers with actual software. For this reason, developing native mobile Apps with Kotlin will be the main focus of this blog, and you can expect various articles about building layouts, adding functionality, polishing your app, integrating with Java, compiling from Java to Kotlin, and finally publishing your end product.

I hope to see you in the next post of this series where we will take a look at the basics of Android Studio and maybe touch upon some Kotlin code already!

Stay tuned…

Cheers.