简体   繁体   English

Android 从 MainActivity 向 class 发送数据

[英]Android sending data to class from MainActivity

i'm creating some Android app, where user add his data, and app will work with it.我正在创建一些 Android 应用程序,用户在其中添加他的数据,应用程序将使用它。 To work i need to write data to SomeClass.kt , from MainActivity.kt .为了工作,我需要从MainActivity.kt将数据写入SomeClass.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:我试图用 Intent 来做,但它给了我 null (我猜,如果 Intent 没有得到 startActivity 选项,它不会发送“putExtra”数据。或者可能是我写 getIntent 错误,但它在第二个活动中提供数据。所以,问题是:我如何将数据从 MainActivity 发送到 SomeClassFile.kt?我的代码:

MainActivity.kt : 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 :数据类.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!")在另一个活动中,使用与DataClass.kt中相同的代码,我得到了我的文本(两个来自 EditText 和“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''.另外,我可以将我的信息写入 .txt 文件并尝试从 this.txt 文件中获取 class 中的数据,但是当我尝试在“类”文件中打开它时,出现“未解决的参考:openFileInput”错误.

you need context or activity to get instance of "intent", but since you are using separate class you can go with this -您需要上下文或活动来获取“意图”的实例,但由于您使用单独的 class 您可以使用 go -

  1. class DataClass(private val context: WeakReference<Context>) { val callerIntent get() = context.get()?.intent }

to make object of DataClass -制作 DataClass 的 object -

val dataClassX = DataClass(WeakReference(this@YOUR_ACTIVITY_CLASS_NAME))

where "this" is reference of your activity / or use getActivity() in fragments.其中“this”是您的活动的引用/或在片段中使用 getActivity()。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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