从分离的片段中获取上下文?
Get context from detached fragment?
我正在尝试从一个分离的片段中初始化一个从 SQLiteOpenHelper
派生的 class 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)
}
如有任何帮助,我们将不胜感激!
您需要在 onAttach()
中初始化 DatabaseHandler
private lateinit var db2: DataBaseHandler
override fun onAttach(context: Context) {
super.onAttach(context)
db2 = DataBaseHandler(context)
}
我正在尝试从一个分离的片段中初始化一个从 SQLiteOpenHelper
派生的 class 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)
}
如有任何帮助,我们将不胜感激!
您需要在 onAttach()
DatabaseHandler
private lateinit var db2: DataBaseHandler
override fun onAttach(context: Context) {
super.onAttach(context)
db2 = DataBaseHandler(context)
}