Search code examples
androidkotlinandroid-fragmentsandroid-context

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!


Solution

  • 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)
    }