Daniel
Daniel

Reputation: 3

Get context from detached fragment?

I am trying to initialize a class DataBaseHandler derived from SQLiteOpenHelper, which takes context as a constructor value, from a detached fragment. I've tried fixing it like the answer in this question suggests, however override fun onAttach() doesn't get called. My code:

class CustomFragment : Fragment() {

    /* first attempt to initialize DBHandler. I get an exception saying the fragment is not 
       attached to the context */
    private var db1: DataBaseHandler = DataBaseHandler(requireContext())

    // variables for second attempt to initialize DBHandler (after onAttach)
    private lateinit var fragmentContext: Context
    private lateinit var db2: DataBaseHandler

    override fun onAttach(context: Context) {
        super.onAttach(context)
        fragmentContext = context
    }
    
    // I get an exception, saying that context is not initialized
    db2 = DataBaseHandler(context)
    
} 

Any help would be appreciated!

Upvotes: 0

Views: 103

Answers (1)

akhil nair
akhil nair

Reputation: 1551

You need to initialize the DatabaseHandler inside the onAttach()

private lateinit var db2: DataBaseHandler

override fun onAttach(context: Context) {
    super.onAttach(context)
    db2 = DataBaseHandler(context)
}

Upvotes: 1

Related Questions