Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin Set Global Variable in Global Class

Tags:

android

kotlin

I'm new to Kotlin. And I need a help that I can't understand to java and kotlin.

For Java I made it. But for kotlin I can't The thing is, I create a Global kotlin class public class Global : Application()

In MainFest I declared that android:name=".Global"

and in Global Class I declared a variable:

public class Global : Application() {
    open var homeAPIResponse: String = "defaultValue"
}

When I set to this global variable any value, it's won't save and when I fetch the value always it's showing default value. I can't understand the java type getter and setter methods in kotlin. Please help me.

I tried that:

global = Global()
global.homeAPIResponse  = "2nd Text"

Log.d("testingTag", "Testing modified response >>>> " + global.homeAPIResponse)

In log it's always showing the defaultvalue.

========================================================================= Guys, my purpose is to save some value globally that, after moves one activity to another, the value will not erase.

Please help me with proper described example cause I searched a lot on stack overflow. and coudn't get it.

Thanks in Advance

like image 280
Sanchyan Chakraborty Avatar asked Dec 17 '22 13:12

Sanchyan Chakraborty


2 Answers

Maybe try like this:

public class Global : Application() {
    companion object {
        @JvmField
        var homeAPIResponse: String = "defaultValue"
    }
}

In other activity:

Global.homeAPIResponse = "new value"
like image 72
alexrnov Avatar answered Dec 21 '22 11:12

alexrnov


It seems you are creating the Global() application manually; you shouldn't be doing this.

The one Application class is created automatically when your app starts.

You want it as a global variable? Do the answer suggested by having:

companion object {
    var globalVariable = "initial value"
}

Put that inside the Global() class. Don't make a new Global() instance manually. Instead in your activity simply call Global.globalVariable = "your new value"

Also, you can make it what kotlin calls a "Top Level Variable". Declare it above the Global class declaration, as follows:

var yourGlobalVariable = "default text"

class Global : Application () {

 // etc.

This can be used anywhere. Start typing it in your application (without Global, just on its own), and it will import.

edit

If your purpose is to have a global variable that persists between activities, doing it using a class (even the application class) really isn't advisable.

Have you considered SharedPreferences?

Get with

PreferenceManager.getDefaultSharedPreferences(context).getString("key to access with", "default value")

And store with

PreferenceManager.getDefaultSharedPreferences(context).edit().putString("key to access with", "your new value").apply()
like image 25
Vin Norman Avatar answered Dec 21 '22 10:12

Vin Norman