uzzi
uzzi

Reputation: 11

Kotlin changing value with button click

I have tried to make a button that subtracts from the "SavingsAccount" and adds to the "MainAccount" but sadly when i click the "Transfer" button nothing happens :( any help would be appreciated.

import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val savingsAccount = BankAccount(name = "uzzi", amount = 50, accountType = "SAVING")
        val mainAccount = BankAccount(name = "uzzi", amount = 100, accountType = "MAIN")

        var users = mutableListOf(savingsAccount, mainAccount)

        textView3.text = ""
        for (user in users){
            textView3.append("${user.name} ${user.amount} ${user.accountType}\n")
            }

        var Convert = findViewById<Button>(R.id.transfer_Saving)
        transfer_Saving.setOnClickListener{
            users[0].subtractAmount(50)
            users[1].addAmount(50)

       }
        }
    }

this a second kotlin file

package com.example.oboppgave4344 
 class BankAccount (var name: String, var amount: Int, var accountType: String){
 fun subtractAmount(subtract: Int) = amount - subtract
 fun addAmount(add: Int) = amount + add
}

Upvotes: 1

Views: 874

Answers (1)

cactustictacs
cactustictacs

Reputation: 19534

Your subtractAmount and addAmount functions aren't actually changing the values in your BankAccount class, they're just calculating a result (and returning it).

You want to do something like

fun subtractAmount(subtract: Int) {
    amount = amount - subtract
}

which you can shorten to amount -= subtract if you like!

Upvotes: 2

Related Questions