-2

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
yml
  • 11
  • 3

1 Answers1

0

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.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Adding to the answer, this is a working example: `val week = (application as App).getNextWeek()`. Assuming that `App` is already referenced in the manifest and above code is executed in the scope of `Activity`. – broot Oct 04 '21 at 08:24
  • I'm just a junior and I don't know why the methods I defined in the class App don't work and now I'm modifying the variables in the application in the activity. I actually tried to use a single instance before asking the question, but it didn't work, so I had to ask for help.I will delete this question soon – yml Oct 04 '21 at 09:27