Search code examples
androidkotlinglobal-variables

I can't change a public variable Kotlin


I try to change a public variable in kotlin but I can't. When I receive the variable in another script, it has not changed. I print the variable in the second script but then it says zero. I have no idea why. Please help me. I'm stuck. Here is my code:

package com.backal.bingo

import android.content.Intent
import android.os.Bundle
import android.util.Log.d
import android.view.View
import androidx.appcompat.app.AppCompatActivity

class AddFavourActivity: AppCompatActivity() {
    public var clicked = 0;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.add_favour)

        val alt1: View = findViewById(R.id.alt1)
        val alt2: View = findViewById(R.id.alt2)
        val alt3: View = findViewById(R.id.alt3)
        val alt4: View = findViewById(R.id.alt4)
        val alt5: View = findViewById(R.id.alt5)
        val alt6: View = findViewById(R.id.alt6)
        val alt7: View = findViewById(R.id.alt7)

        alt1.setOnClickListener {
            var clicked = 50
            startActivity(Intent(this, EnterPasswordActivity::class.java))
        }

        alt2.setOnClickListener {
            var clicked = 80
            d("*", "Clicked is: $clicked")
            startActivity(Intent(this, EnterPasswordActivity::class.java))
        }

        alt3.setOnClickListener {
            startActivity(Intent(this, EnterPasswordActivity::class.java))
            clicked = 100
        }

        alt4.setOnClickListener {
            startActivity(Intent(this, EnterPasswordActivity::class.java))
            clicked = 300
        }

        alt5.setOnClickListener {
            startActivity(Intent(this, EnterPasswordActivity::class.java))
            clicked = 500
        }

        alt6.setOnClickListener {
            startActivity(Intent(this, EnterPasswordActivity::class.java))
            clicked = 100
        }

        alt7.setOnClickListener {
            startActivity(Intent(this, EnterPasswordActivity::class.java))
            clicked = 1000
        }

    }


}


Solution

  • every time you are doing var clicked = 50 you're declaring a new variable (even if it's the same name) so just remove the var :

    clicked = 50
    

    something else you might want to consider is to rather make use of a companion object :

     companion object {
        var clicked = 0
    }
    

    then you can use this variable everywhere, by just using: AddFavourActivity.clicked

    or AddFavourActivity.clicked = 50

    A companion object will ensure the same instance of the variable is used everywhere