Issue
i'm creating some Android app, where user add his data, and app will work with it. To work i need to write data to SomeClass.kt
, from MainActivity.kt
. I tried to do it with Intent, but it give null to me (I guess, if Intent dont get startActivity option, it will not send "putExtra" data. Or may be i write getIntent wrong, but it give data in second activity. So, the question is: How i can send data from MainActivity to SomeClassFile.kt? My codes :
MainActivity.kt:
...
val name = findViewById<EditText>(R.id.editTextTextPersonName)
val sname = findViewById<EditText>(R.id.editTextTextPassword)
val i = Intent(this@MainActivity, DataClass::class.java)
val bundle = Bundle()
bundle.putString("login", name.toString())
bundle.putString("email", sname)
bundle.putString("test", "hello world")
myIntent.putExtra("MyPackage", bundle)
...
DataClass.kt:
class DataClass {
val callerIntent = intent // <-- Error is here, 'Unresolved reference: intent'
val packageFromCaller = callerIntent.getBundleExtra("MyPackage")
val contact = packageFromCaller!!.getString("login")
val email = packageFromCaller!!.getString("email")
val test = packageFromCaller!!.getString("test")
}
In another Activity, using same code as in DataClass.kt
i got my text (two from EditText and "Hello world!")
Also, i can write my information to .txt file and try to get data in class from this .txt file, but when i try to open it in "class" file, i got an error with ''Unresolved reference: openFileInput''.
Solution
you need activity to get instance of "intent", but since you are using separate class you can go with this -
class DataClass(private val activity: WeakReference<Activity>) { val callerIntent get() = activity.get()?.intent }
to make object of DataClass -
val dataClassX = DataClass(WeakReference(this@YOUR_ACTIVITY_CLASS_NAME))
where "this" is reference of your activity / or use getActivity() in fragments.
Answered By - Rishabh Shukla
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.