androidmember-variables

How to pick up values from MainActivity in another class


I assume it would be a good idea to put long-winded functions in a class other than MainActivity. However, I'm having difficulty using values from MainActivity in a separate class.

To test this I have MainActivity as

package com.example.separateclasstest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class MainActivity : AppCompatActivity() {

    var mName = ""
    var mRadius = 0


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

        mName = "Mary"
        mRadius = 50

        Log.i("sct","Name in Main: $mName")
        Log.i ("sct", "Radius in Main: $mRadius")

        SupportRoutines().supportFunction()
    }
}

and SupportRoutines.kt

package com.example.separateclasstest

import android.util.Log

class SupportRoutines {
    var mSupportName = ""
    var mSupportRadius = 0

    fun supportFunction() {
        mSupportName = MainActivity().mName
        mSupportRadius = MainActivity().mRadius
        Log.i("sct", "Name in 2nd class: $mSupportName")
        Log.i ("sct", "Radius in 2nd class: $mSupportRadius")
    }

}

When I run this, no errors are reported but the string variable received by SupportRoutines is a blank string and the integer variable is zero, as shown in LogCat:

2020-06-12 16:22:31.326 11393-11393/com.example.separateclasstest I/sct: Name in Main: Mary
2020-06-12 16:22:31.326 11393-11393/com.example.separateclasstest I/sct: Radius in Main: 50
2020-06-12 16:22:31.327 11393-11393/com.example.separateclasstest I/sct: Name in 2nd class: 
2020-06-12 16:22:31.328 11393-11393/com.example.separateclasstest I/sct: Radius in 2nd class: 0

How do I refer correctly to the members of MainActivity?


Solution

  • Never create an instance of an activity yourself, as you are doing in SupportRoutines. Either pass in your MainActivity instance to supportFunction() as a parameter or pass in the name and radius as individual parameters to supportFunction().