在哪里初始化lateinit?给出错误“ kotlin.UninitializedPropertyAccessException:lateinit属性数据库尚未初始化”

时间:2019-10-02 14:34:14

标签: android kotlin

MainActivity.kt

 class MainActivity : AppCompatActivity() {
  lateinit var db:Database
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
       db=Room.databaseBuilder(applicationContext,Database::class.java,"Users").build() //Error is shown here
    }

}

AddUserFragment.kt

class AddUserFragment : Fragment() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {


    // Inflate the layout for this fragment
    val view= inflater.inflate(R.layout.fragment_add_user, container, false)

    view.btn_add.setOnClickListener {
        val id=et_Uid.text.toString()
        val name=et_Name.text.toString()
        val email=et_Email.text.toString()

        val users=Users(id,name,email)

        val mainActivity=MainActivity()
        mainActivity.db.myDao().addUser(users) //Error is shown here
        Toast.makeText(activity,"Added",Toast.LENGTH_LONG).show()
    }

    return  view
}}

在哪里初始化db以便不获取kotlin.UninitializedPropertyAccessException:lateinit属性db尚未初始化

1 个答案:

答案 0 :(得分:1)

您正在创建MainActivity的新实例,这不是必需的!

每个片段都有一个与它们关联的activity实例

只需将activity转换为MainActivity

(activity!! as MainActivity).db.myDao().addUser(users)