简体   繁体   中英

How to pass the value of a variable in one class to another in Kotlin?

I want to pass the value of a variable which has been initialized in one class to another class since I need that value to pass it to an API I am using for further results. Is there a way I can do that?

class LogInScreen: AppCompatActivity() { 

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


     getusername = findViewById(R.id.usernameEditText)
            var username = usernameEditText.text
            
            getpass = findViewById(R.id.passEditText)
            var pass = passEditText.text
            
      }

 }

I have an API in my application which generates an Id when the username and password is given to the API. I save this value in a variable:

val myId = "somevalue"

I want to access the value of myId in another class. The value is needed since I want to concatenate it to the other APIs I use in my application. How can I achieve this?

Why don't you use an interface? It's indeed a great approach to share data between different classes you can do something like this

    class LogInScreen(private val listener :onDataRecieved): AppCompatActivity() { 

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


     getusername = findViewById(R.id.usernameEditText)
            var username = usernameEditText.text
            
            getpass = findViewById(R.id.passEditText)
            var pass = passEditText.text
            listener.onUsernameRecieved(username)
            
      }
      interface onDataRecieved {
        fun onUsernameRecieved(username: String)
    }
    }

Now you just need to implement the interface wherever you want and your username will be available

    class SampleFragment : Fragment(R.layout.SampleFragment), 
    LogInScreen.onDataRecieved {
    private const val TAG = "MyFragment"
    override fun onUsernameRecieved(username: String) {
      Log.i(TAG, "$username is available here!")
    }
}

I hope it would be helpful.

You can create instance if that class and access it any class.For example if your myid stored in myApplication class like below.


class myApplication() {
      myid = "somevalue"
}

Then you can access it from any calss like,

val app = myApplication()
print(app.myid)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM