Felipe Campos
Felipe Campos

Reputation: 31

How to pass a context as a parameter

I'm an beginner in kotlin and im trying to pass a context as a parameter, but isnt working... these are my codes:

FUNCTION saveDatabase

    private fun saveDatabase(context : Context){
    val fightersName = Match(1, fighter1.toString(), fighter2.toString(),
            minute.toInt(), round.toInt())

    val db = DBContract(context)
    db.insertData(fightersName)
    }

CALLING THE FUNCTION

   saveDatabase(context)

WARNING

Typemismatch Required: Context Found: Context?

This class is a fragment that extends of a Fragment()

Upvotes: 2

Views: 3648

Answers (4)

Raymond Arteaga
Raymond Arteaga

Reputation: 4673

If you are new in Android with kotlin you will surely need an "always available" context. This is the way:

class App : Application() {
companion object {
    lateinit var instance: App
}

override fun onCreate() {
    super.onCreate()
    instance = this
}

}

then you just need to pass:

val db = DBContract(App.instance)

Be sure of modifying the manifest:

 <application
    android:name=".App"
    ...>

Upvotes: 0

Abner Esc&#243;cio
Abner Esc&#243;cio

Reputation: 2785

it so easy. Try as follow

private fun saveDatabase(context : Context?){
    val fightersName = Match(1, fighter1.toString(), fighter2.toString(),
            minute.toInt(), round.toInt())

    val db = DBContract(context)
    db.insertData(fightersName)
}

Upvotes: 0

Debanjan
Debanjan

Reputation: 2836

your function requires a non null Context object, whereas you are calling it with a nullable and mutable Context object. If you are sure your context is not null, call

saveDatabase(context!!)

!! means that you vouch for the object to be non null

Or you can check your function for safety, then change your function to

private fun saveDatabase(context : Context?){
    if(context != null){
    val fightersName = Match(1, fighter1.toString(), fighter2.toString(),
            minute.toInt(), round.toInt())

    val db = DBContract(context)
    db.insertData(fightersName)
    }
    }

Upvotes: 1

zsmb13
zsmb13

Reputation: 89668

The getContext method that you're accessing as the context property in Kotlin has a nullable type Context? - since it will return null when your Fragment isn't attached to an Activity.

One way to deal with the error is to first fetch its value, and perform a null check before you call your function:

val context = context
if (context != null) {
    saveDatabase(context)
}

The same check using let, in two different forms:

context?.let { ctx -> saveDatabase(ctx) }
context?.let { saveDatabase(it) }

You can also use requireContext if you are absolutely sure that your Fragment is attached to an Activity - this returns a non-nullable Context, or throws an exception if there isn't one available.

saveDatabase(requireContext())

Upvotes: 1

Related Questions