如何通过一种方法更新整个 kotlin class 中的 var,然后使用另一个方法调用检索它更新

How can I update a var inside a whole kotlin class through a method and then retrieve it updated with another method call

我写了一个 kotlin class 有一个被覆盖的乐趣和一个有趣的更新 var 到 class 范围(我是 Kotlin 的新手!)

class mySampleClass: sampleReference(){
    var varToBeUpdated:String = "my string" //var in class scope to be updated

    fun updateMyVar(gotString:String){

        //I tried this, it didn't work
        this.varToBeUpdated = gotString
        // also this didn't work
        varToBeUpdated = gotString

    }

    override fun sample(context: Context, intent: Intent){
        //here i need my varToBeUpdated with new string
        runSomeThing(varToBeUpdated)
        //some work to be done here
    }
}

在我调用方法的地方:

myObject.updateMyVar("new string")
myObject.sample()

我想知道如何更新我需要的变量,因为我无法在 "fun sample" 中添加新的参数,因为它覆盖了 class 方法

提前致谢,向大家致以最诚挚的问候:)



更新:添加我的实际代码,因为 class 在我调用覆盖方法时似乎无法保持正确的更新值:

这是我的 BroadcastReceiver,用于检查下载何时完成并执行某些操作

class DownloadBroadcastManager: BroadcastReceiver() {

    var myClassFilename:String = "default"
    var myClassExtension:String = ".default"

    override fun onReceive(context: Context, intent: Intent) {
        val action = intent.action

        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == action) {
            //Show a notification
            // here there's a log to check if var are updated
            println("myTag - variables $myClassFilename, $myClassExtension")

            Toast.makeText(context, "Download of $myClassFilename$myClassExtension completed", Toast.LENGTH_LONG).show()
            // richiama azioni come player o display image o altro?

            //player
            var uri = Uri.parse (Environment.getExternalStorageDirectory().getPath() + "/Download/$myClassFilename$myClassExtension") //myClassExtension is ".mp3", dot is included, however it seems class is re-intialized as i call the method
            println("myTag - uri: $uri")
            println("myTag - context: $context")

            var mPlayer = MediaPlayer() // I added this declaration (that's be re-done later) cause I had a problem in making the player running (of course giving it a valid path to a valid file). Now this is "junk code"
            mPlayer.stop()
            mPlayer.reset()
            mPlayer.release()
            mPlayer = MediaPlayer.create(context, uri) // here there's the proper declaration + initialization
            mPlayer.start()

        }
    }
}

这是我的 DownloaderClass 的部分...

var brReceiver = DownloadBroadcastManager()
    // shows when download is completed
    println("myTag - ${brReceiver.myClassFilename}, ${brReceiver.myClassExtension}: originals") //here shows the default: it's right
    val intent = Intent(context, MainActivity::class.java)
    brReceiver.myClassFilename = myTitle // inject filename
    brReceiver.myClassExtension = ".mp3" // inject file extension
    println("myTag - ${brReceiver.myClassFilename}, ${brReceiver.myClassExtension}: modified") // here it shows my class property as correctly updated

    brReceiver.onReceive(context, intent) // here, as calling the override fun, it get back to default value of the property

根据 kotlin 文档,您可以像这样为任何变量定义 gettersetter 方法:

var <propertyName>[: <PropertyType>] [= <property_initializer>]
[<getter>]
[<setter>]

在你的情况下可能是这样的:

var varToBeUpdated:String = "my string"
    get() = field
    set(value) { field = value }

您只需执行以下操作:

  1. 去掉updateMyVar函数:

    class MySampleClass: SampleReference(){
        var varToBeUpdated:String = "my string" //var in class scope to be updated
    
        override fun sample(context: Context, intent: Intent){
            //here i need my varToBeUpdated with new string
            runSomeThing(varToBeUpdated)
            //some work to be done here
        }
    }
    
  2. 直接更新varToBeUpdated属性:

    val myObject = MySampleClass()
    myObject.varToBeUpdated = "new string"
    myObject.sample()
    

更新: 如果您调用 brReceiver.onReceive(...)DownloadBroadcastManager 中的值会更新。但你不应该那样做。 Android 框架 会为您调用它。当它发生时,将创建 DownloadBroadcastManager class 的新实例并设置默认值。我们使用 Intents 将数据传递给 BroadcastReceiver,例如创建BroadcastReceiver时调用intent.putExtra("filename", "yourFileName"),在onReceive()函数中调用intent.getStringExtra("filename")获取值。 Here is how to pass/get data to/from BroadcastReceiver

好的,首先要感谢 M.SamiAzar,尤其要感谢 Sergey,感谢他们的回答和难以置信的耐心! 不幸的是,由于框架重新初始化,BroadcastReceiver 似乎也丢失了我之前放入 Intent 变量中的任何额外内容。 我终于解决了这个问题,让我检索我需要的字符串,只需将一行文本写入内部存储中的文件并在我的 BroadcastReceiver class 中检索它。 这是代码:

这是我在 BroadcastReceiver 中的 "onReceive" 方法 class

 override fun onReceive(context: Context, intent: Intent) {
    val action = intent.action
    Log.i("Receiver", "myTag - Broadcast received: " + action)
    var myFilename = "deafult"

    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE == action) {

        // read the previously created file from internal storage
        var fileInputStream: FileInputStream? = null
        fileInputStream = context.openFileInput("storeDownloadedData")
        var inputStreamReader: InputStreamReader = InputStreamReader(fileInputStream)
        val bufferedReader: BufferedReader = BufferedReader(inputStreamReader)

        // here setting string var and stringbuilder var to catch the text updated outside the while loop
        val stringBuilder: StringBuilder = StringBuilder()
        var text: String? = null
        var sumText:java.lang.StringBuilder? = null
        // while loop for reading the file line by line (in this case the file can contains just one line a time)
        while ({ text = bufferedReader.readLine(); text }() != null) {
            sumText = stringBuilder.append(text)
        }

        // convert stringBuilder to a list of string splitting the original string obtained by file reading
        var secondText:String = "default"
        println("myTag - text: $text, $sumText")
        if (sumText != null){
            secondText = sumText.toString()
            var listFromText = secondText.split(",")
            // set filename to the title contained in the string
            myFilename = listFromText[0]
        }

        //player - finally play the file retrieving the title from the file in internal storage
        var uri = Uri.parse (Environment.getExternalStorageDirectory().getPath() + "/Download/$myFilename.mp3")
        println("myTag - uri: $uri")
        println("myTag - context: $context")

        var mPlayer = MediaPlayer.create(context, uri)
        mPlayer.start()

    }

这是我的 DownloadManager 添加的代码 class:

// strore into an internal storage file the data of title and extensione for the file's gonna be downloaded
    val myStoredFile:String = "storeDownloadedData"
    val data:String = "$myTitle,.mp3"
    val fileOutputStream: FileOutputStream
    // write file in internal storage
    try {
        fileOutputStream = context.openFileOutput(myStoredFile, Context.MODE_PRIVATE)
        fileOutputStream.write(data.toByteArray())
    }catch (e: Exception){
        e.printStackTrace()
    }

    // it notifies when download is completed
    val intent = Intent(context, MainActivity::class.java)
    var brReceiver = DownloadBroadcastManager()

我不知道这是不是 "ortodox",但它似乎在 atm 上有效 :)