Search code examples
androidandroid-activitymember

Referring to a member of MainActivity in another class


My MainActivity begins like this:

class MainActivity : AppCompatActivity() {
val mDBAdapter = DBAdapter(this, "nearbydata")

I want to use the database adapter in another class PickFromList (which extends ListActivity).

I don't seem to be able to refer to it as MainActivity.mDBAdapter. I understand that this is because there are no instances of the MainActivity class.

According to How to reference the current or main activity from another class this is "a problem that lots of developers have". The top answer in that thread reads

If you already have a valid context, just use this: Activity activity = (Activity) context;

Unfortunately to someone as inexperienced as me that is not helpful. How do I know whether I have a valid context? If I don't have one how do I get one?

If I try pasting that code into my PickFromList class, Quick Fix tells me that it "cannot resolve symbol 'context'" and offers to create a local variable 'context'. But that doesn't help.


Solution

  • You should't refer from one activity to another because it can cause memory leaks and crashes (https://android.jlelse.eu/9-ways-to-avoid-memory-leaks-in-android-b6d81648e35e) Then you should share this DBAdapter instance via global state or with dependency injection. And in this case you can use application context to instantiate DBAdapter. For example you could use you App class

    class App : Application() {
    
        companion object {
            lateinit var adapter: DBAdapter
        }
    
        override fun onCreate() {
            super.onCreate()
            adapter = DBAdapter(this)
        }
    }
    

    It's safe because you have just one instance of App class and therefore one Application Context. And after this you can use adapter like App.adapter in your activities.

    But this is rough solution. Better way is providing you dependencies via Dependency injection (https://developer.android.com/training/dependency-injection)