kotlin С无法通过sharedPreferences从另一个片段获取数据

wnavrhmk  于 2023-05-07  发布在  Kotlin
关注(0)|答案(1)|浏览(116)
//FIRST FRAGMENT

class StaffProfileFragment : Fragment() {
    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_staff_profile, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val staffName = view.findViewById<TextView>(R.id.staffName)
        val staffSurname = view.findViewById<TextView>(R.id.staffSurname)
        val sharedPreferences = activity?.getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        staffName?.text = sharedPreferences?.getString("StaffName", "Имя")
        staffSurname?.text = sharedPreferences?.getString("StaffSurname", "Фамилия")
        val exitButton = view.findViewById<Button>(R.id.exitButton)
        exitButton.setOnClickListener {
        FirebaseAuth.getInstance().signOut()
            parentFragmentManager?.beginTransaction()
                ?.replace(R.id.club_placeholder, ProfileFragment.newInstance())
                ?.addToBackStack(null)?.commit()
        }
        val goToStaffData = view.findViewById<ConstraintLayout>(R.id.goToStaffData)
        goToStaffData.setOnClickListener {
            parentFragmentManager?.beginTransaction()
                ?.replace(R.id.club_placeholder, StaffDataFragment.newInstance())
                ?.addToBackStack(null)?.commit()
        }
        val groupWorkouts = view.findViewById<ConstraintLayout>(R.id.groupWorkouts)
        groupWorkouts.setOnClickListener {
            parentFragmentManager?.beginTransaction()
                ?.replace(R.id.club_placeholder, CreateWorkoutsFragment.newInstance())
                ?.addToBackStack(null)?.commit()
        }
        val goToChangePassword = view.findViewById<ConstraintLayout>(R.id.goToChangePassword)
        goToChangePassword.setOnClickListener{
            parentFragmentManager?.beginTransaction()
                ?.replace(R.id.club_placeholder, ChangePasswordFragment.newInstance())
                ?.addToBackStack(null)?.commit()
        }
    }


    companion object {
        fun newInstance() = StaffProfileFragment()
    }
}

//SECOND FRAGMENT

class StaffDataFragment : Fragment() {
    val sharedPreferences = activity?.getSharedPreferences("myPrefs", Context.MODE_PRIVATE)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_staff_data, container, false)
    }

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

        val switch: Switch = view.findViewById(R.id.staffDataSwtcher)
        val editTextName: EditText = view.findViewById(R.id.editTextStaffName)
        val editTextSurname: EditText = view.findViewById(R.id.editTextStaffSurname)
        val backButton: TextView = view.findViewById(R.id.staffDataBackButton)
        editTextName.isEnabled = false
        editTextSurname.isEnabled = false

        backButton.setOnClickListener{
            parentFragmentManager?.beginTransaction()
                ?.replace(R.id.club_placeholder, StaffProfileFragment.newInstance())
                ?.commit()
        }

        switch.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                // если Switch включен, делаем EditText доступными для ввода
                editTextName.isEnabled = true
                editTextSurname.isEnabled = true
            } else {
                // если Switch выключен, делаем EditText недоступными для ввода
                editTextName.isEnabled = false
                editTextSurname.isEnabled = false
            }
        }

        val saveButton: Button = view.findViewById(R.id.saveStaffDataName)
        saveButton.setOnClickListener {
            val name = editTextName.text.toString()
            val surname = editTextSurname.text.toString()

            
            val editor = sharedPreferences?.edit()
            editor?.putString("StaffName", name)
            editor?.putString("StaffSurname", surname)
            editor?.apply()

            
            switch.isChecked = false
            editTextName.isEnabled = false
            editTextSurname.isEnabled = false
        }
    }

    companion object {
        fun newInstance() = StaffDataFragment()
    }
}

当我在EditText中输入片段上的数据并使用名和姓并单击保存按钮时,数据应该保存在SharedPreferences中,然后在上一个片段上,这些数据应该显示在TextView中
但无论我如何尝试获取这些数据,默认数据仍然存在。我也尝试在onResume和onStart中获取这些数据,但一切都保持不变

mnowg1ta

mnowg1ta1#

问题就在这里:

class StaffDataFragment : Fragment() {
    val sharedPreferences = activity?.getSharedPreferences("myPrefs", Context.MODE_PRIVATE)

您正在对空Activity使用空安全的?.调用,因此sharedPreferences为空,您无法使用它。
?.的意思是你 * 可能 * 希望某事发生。如果您发现自己不得不使用?.来做一些肯定会发生的事情,那么您需要退后一步,考虑一下您做错了什么。在这种情况下,就是您试图从Activity中获取某些内容,而此时该内容还不可用。
SharedPreferences在您使用时没有充分的理由可以为空,因此您不应该将其放在可为空的属性中。
您不能获得依赖于Activity作为属性声明的内容,因为当片段仍在示例化时,片段尚未附加到Activity。您应该将这行代码移到onViewCreated()内部,并将所有?.更改为.。您可以将activity替换为requireActivity(),这样它就不会为空。requireActivity()可以安全地在片段的视图生命周期内调用内部函数。

相关问题