-1

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?

Shay Kin
  • 2,539
  • 3
  • 15
  • 22
sara
  • 19
  • 1
  • 8
  • I found this one, it does look similar :) hope this helps https://stackoverflow.com/questions/60394914/kotlin-get-a-variable-value-from-one-class-to-another – Madona wambua Apr 26 '21 at 02:29
  • 1
    There are several ways for that. 1. You can store some variables to singleton class. then access that variable from another class. [https://stackoverflow.com/a/58693974/3494153](https://stackoverflow.com/a/58693974/3494153) 2. Use Shared Preferences. [https://developer.android.com/training/data-storage/shared-preferences](https://developer.android.com/training/data-storage/shared-preferences) – Song Junwoo Apr 26 '21 at 02:58

1 Answers1

0

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.