Ameena Shafeer
Ameena Shafeer

Reputation: 626

Unresolved reference: this@SplashScreen while accessing SplashScreen from inner class

I am trying to access SplashScreen activity from an inner class as shown below. But I cant resolve this@SplashScreen

class SplashScreen : AppCompatActivity() {

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

    }

    private class SplashTimerTask : TimerTask() {

        override fun run() {
            val mainIntent = Intent(this@SplashScreen, LoginActivity::class.java)
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(mainIntent)
            [email protected]()
        }
    }
}

Upvotes: 0

Views: 208

Answers (3)

Tenfour04
Tenfour04

Reputation: 93699

Aside from passing the parent class as a parameter (the verbose, sloppy option), and marking the timer class inner, the third option is an anonymous class:

private val splashTimerTask = object: TimerTask() {

    override fun run() {
        val mainIntent = Intent(this@SplashScreen, LoginActivity::class.java)
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(mainIntent)
        finish()
    }
}

A fourth option is to use a coroutine instead of a Timer and TimerTask:

private fun openLoginActivity(delay: Long) {
    lifecycleScope.launch {
        delay(delay)
        val mainIntent = Intent(this@SplashScreen, LoginActivity::class.java)
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(mainIntent)
        finish()
    }
}

Upvotes: 0

Ameena Shafeer
Ameena Shafeer

Reputation: 626

this could be resolved by changing the SplashTimerTask like below

    private class SplashTimerTask(val splash: SplashScreen) : TimerTask() {

    override fun run() {
        val mainIntent = Intent(splash, LoginActivity::class.java)
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(splash, mainIntent, null)
        splash.finish()
    }
}

and calling in SplashScreen like below

_splashTimerTask = SplashTimerTask(this@SplashScreen)

Upvotes: 0

Yurii
Yurii

Reputation: 685

Try this

private class SplashTimerTask(val splash: SplashScreen) : TimerTask() {

    override fun run() {
        val mainIntent = Intent(splash, LoginActivity::class.java)
        mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        startActivity(mainIntent)
        splash.finish()
    }
}

or

inner class SplashTimerTask : TimerTask() {

        override fun run() {
            val mainIntent = Intent(this@SplashScreen, LoginActivity::class.java)
            mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(mainIntent)
            [email protected]()
        }
    }

Upvotes: 2

Related Questions