Home > front end >  (Android - Kotlin) A variable value is always null
(Android - Kotlin) A variable value is always null

Time:12-12

I made a functions.kt file for global variables and I made that:

import android.app.Application

class variable : Application() {
    var currentLesson: String? = null
}

After that, I used it in main.kt like so:

class MainActivity : AppCompatActivity() {

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

        button: Button = findViewById(R.id.button1)
        var functions = variable()
        var currentLesson = functions.currentLesson

        button.onClickListener {
            currentLesson = "text"
        }
    }

    override fun onBackPressed() {
        someview: View =
        findViewById(R.id.view1)
        var functions = variable()
        var currentLesson = functions.currentLesson

        if (currentLesson == "text") {
             someview.visibility = View.VISIBLE
        }
    }

}

In onBackPressed() it's always null. But not in onCreate(). Where is the problem?

CodePudding user response:

Every time you call variable() you are creating a new instance of the class variable so it has its own memory and state that it's holding.

Incidentally, you should not be subclassing Application to create this class, since your simple data holder is not an Application!

If you want a class to hold some shared state for the whole app, that's commonly called a singleton (a class with only one instance), and you can easily create one in Kotlin using an object instead of class.

object Variable {
    var currentLesson: String? = null
}

Then when you use it in your Activity, you can call it directly with Variable.currentLesson without having to create an instance of the class.

Alternatively, you can put the variable outside of any class, and it will be a global property that can be accessed from anywhere. In my opinion, that's kind of an ugly solution because it pollutes the namespace.

Note, you should be careful about what you store in global variables like this. It is not good practice to put large, memory-hungry objects in a global variable that will cause that memory to be used for longer than necessary.

Also, it is convention to make class names always start with a capital letter. It will make your code much easier to read and understand, especially in languages like Kotlin which omit the new keyword used for constructor calls.

  • Related