Jackson
Jackson

Reputation: 335

How to start a new activity from a non activity class in Kotlin?

I'm working on an application which reads heart rate from the finger using camera lens. I want after it's done with previewing the image to pass the results to a new Activity. I want to open the next Activity which is Results.kt.

Here is what I've tried so far:

if (Beats != 0) {
    var intent = Intent(this, Results::class.java)
    ContextCompat.startActivity(intent)
}

Upvotes: 0

Views: 677

Answers (2)

Benjamin
Benjamin

Reputation: 7368

As long as you have a proper Context available, you can start your Results as follow:

if (Beats != 0) {
    var intent = Intent(context, Results::class.java)
    context.startActivity(intent)
}

If your non-activity class does not have access to a Context right now, you should inject it somewhere (during creation of your object as a passed-in argument for example).

Upvotes: 1

Niki Trivedi
Niki Trivedi

Reputation: 1786

You can not use this as it's not an Activity and therefore not a Context. You have to provide a proper Context and can also pass flag saying new task:

 if (Beats != 0) {
      var intent = Intent(MyClass.this.context, Results::class.java)
      MyClass.this.context.startActivity(intent)
  }

Here replace MyClass with your class name. Not sure if it will work or not.

Upvotes: 0

Related Questions