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.

Leave a Reply

Your email address will not be published. Required fields are marked *