【问题标题】:Get context from detached fragment?从分离的片段中获取上下文?
【发布时间】:2021-05-08 12:38:42
【问题描述】:

我正在尝试从分离的片段初始化一个派生自SQLiteOpenHelper 的类DataBaseHandler,该类将context 作为构造函数值。 我已经尝试修复它,就像this 问题中的答案所暗示的那样,但是override fun onAttach() 没有被调用。我的代码:

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

任何帮助将不胜感激!

【问题讨论】:

    标签: android kotlin android-fragments android-context


    【解决方案1】:

    你需要在onAttach()里面初始化DatabaseHandler

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

    【讨论】:

      猜你喜欢
      • 2015-05-02
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多