Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreate in abstract parent activity no called in kotlin

Tags:

android

kotlin

I declared a child of MapActivity:

class RecordingActivity : MapActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.d("RecirdingActivity", "InitializeMap") //called
    }

    override fun getView(): Int {
        return R.layout.activity_recording
    }
}

I make a call to start this activity from my main activity:

fab.setOnClickListener {
            Log.d("MainActivity", "fabClick") //called
            startActivity(intentFor<RecordingActivity>())
        }

and I have the abstract activity:

abstract class MapActivity: AppCompatActivity(), OnMapReadyCallback {

    override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
        super.onCreate(savedInstanceState, persistentState)
        setContentView(getView())
        initializeMap()
        Log.d("MapActivity", "InitializeMap")//not called
    }
}

and onCreate method of this activity is never called

I traced it with a debugger and I had the same result. What am I doing wrong?

like image 603
nutella_eater Avatar asked Dec 25 '22 04:12

nutella_eater


1 Answers

there seems to be two solutions:

  1. maybe the onCreate you actually want to override in MapActivity has the signature onCreate(android.os.Bundle):

    abstract class MapActivity: AppCompatActivity(), OnMapReadyCallback {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(getView())
            initializeMap()
            Log.d("MapActivity", "InitializeMap")
        }
    }
    
  2. the documentation of the onCreate(android.os.Bundle, android.os.PersistableBundle) method that is being overridden in MapActivity suggests that persistableMode for the activity in the AndroidManifest.xml needs to be set to persistAcrossReboots for it to be called...but MapActivity is abstract, so you would need to set the attribute for its subclasses instead. in this case that would be RecordingActivity.

    <?xml version="1.0" encoding="utf-8"?>
    <manifest>
        ...
        <application>
            ...
            <activity
                android:name=".RecordingActivity"
                android:persistableMode="persistAcrossReboots"/>
            ...
        </application>
        ...
    </manifest>
    
like image 118
Eric Avatar answered Dec 28 '22 06:12

Eric