Home > Mobile >  Changing the value of a variable defined in an application several times does not work [Android] [du
Changing the value of a variable defined in an application several times does not work [Android] [du

Time:10-04

I have defined an Int variable week in the application class, its initial value is 0, and there are some methods to modify it. I have a button in Main_activity, when I click it, week =1, but when I click the button several times, week is always 1.

My App.kt

class App :Application(){
    var week :Int = 0
    fun getNextWeek(): Int{
        this.week =1
        return this.week
    }
}

This is the code that will be executed when the button is clicked

val week = App().getNextWeek()
println(week)

When click button times,except:

1
2
3
4

CodePudding user response:

You are instantiating a new App for each call (App()), and each instance has its own week variable.

Assuming it's an Android Application, you should never be instantiating it yourself. Assuming you really want to store this data in an application class, rather declare it in your manifest file as the application class, and obtain the single instance with getApplication() of any Context in your app.

  • Related