android onActivityCreated()已被弃用,我认为它导致我的保存联系人功能无法工作,但不知道如何修复它

6pp0gazn  于 2023-04-28  发布在  Android
关注(0)|答案(2)|浏览(338)

我一直在为一个项目开发一个Android应用程序,必须制作一个通信按钮,基本上只是作为联系人应用程序工作。所以我遵循了如何制作它的教程,但他使用了一些过时的库,包括很多生命周期。为了使“保存联系人”按钮在应用程序上工作,他在“onActivityCreated”函数上做了一个ovverride。然而,onActivityCreated已被弃用,我一直在寻找修复它的方法,但无济于事。
下面的代码是我的AddContactDialogFragment.kt类,在那里我试图实际使addcontact发生,所以问题最有可能在那里。你可以看到注解了“onViewCreated”的覆盖,我在看到onActivityCreated被弃用后尝试过。

package com.example.mavhealth.ui

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.mavhealth.R
import com.example.mavhealth.data.Contact
import com.example.mavhealth.databinding.FragmentAddContactDialogBinding
import androidx.lifecycle.DefaultLifecycleObserver

class AddContactDialogFragment : DialogFragment(), DefaultLifecycleObserver {
    private var _binding: FragmentAddContactDialogBinding? = null
    private val binding get() = _binding!!
    private lateinit var viewModel: ContactViewModel

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super<DialogFragment>.onCreate(savedInstanceState)
        setStyle(STYLE_NO_TITLE, android.R.style.Theme_DeviceDefault_Light_Dialog_MinWidth)
        activity?.lifecycle?.removeObserver(this)

        viewModel.result.observe(viewLifecycleOwner, Observer{
            val message = if (it == null) {
                getString(R.string.added_contact)
            }else{
                getString(R.string.error, it.message)
            }
            Toast.makeText(requireContext(),message,Toast.LENGTH_SHORT).show()
            dismiss()
        })
        binding.buttonAdd.setOnClickListener {
            val fullName = binding.editTextFullName.text.toString().trim()
            val contactNumber = binding.editTextContact.toString().trim()
            if(fullName.isEmpty())
            {
                binding.editTextFullName.error = "This is a required field"
                return@setOnClickListener
            }
            if(contactNumber.isEmpty())
            {
                binding.editTextContact.error = "This is a required field"
                return@setOnClickListener
            }
            val contact = Contact()
            contact.name = fullName
            contact.number = contactNumber
            viewModel.addContact(contact)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View?
    {
        _binding = FragmentAddContactDialogBinding.inflate(inflater, container, false)
        viewModel = ViewModelProvider(this)[ContactViewModel::class.java]
        return binding.root
    }
/*
    override fun onViewCreated(view: View, savedInstanceState: Bundle?)
    {
        super.onViewCreated(view, savedInstanceState)
        viewModel.result.observe(viewLifecycleOwner, Observer{
            val message = if (it == null) {
                getString(R.string.added_contact)
            }else{
                getString(R.string.error, it.message)
            }
            Toast.makeText(requireContext(),message,Toast.LENGTH_SHORT).show()
            dismiss()
        })
        binding.buttonAdd.setOnClickListener {
            val fullName = binding.editTextFullName.text.toString().trim()
            val contactNumber = binding.editTextContact.toString().trim()
            if(fullName.isEmpty())
            {
                binding.editTextFullName.error = "This is a required field"
                return@setOnClickListener
            }
            if(contactNumber.isEmpty())
            {
                binding.editTextContact.error = "This is a required field"
                return@setOnClickListener
            }
            val contact = Contact()
            contact.name = fullName
            contact.number = contactNumber
            viewModel.addContact(contact)
        }
    }
*/

    override fun onAttach(context: Context)
    {
        super.onAttach(context)
        activity?.lifecycle?.addObserver(this)
    }

}

这个代码块是我的ContactViewModel.kt类,在这个类中我有一个addContact函数,所以这也可能是出错的地方。

package com.example.mavhealth.ui

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.example.mavhealth.data.Contact
import com.example.mavhealth.data.NODE_CONTACTS
import com.google.firebase.database.FirebaseDatabase

class ContactViewModel: ViewModel()
{
    private val dbContacts = FirebaseDatabase.getInstance().getReference(NODE_CONTACTS)
    private val _result = MutableLiveData<Exception?>()
    val result: LiveData<Exception?> get() = _result
    fun addContact(contact: Contact)
    {
        contact.id = dbContacts.push().key
        dbContacts.child(contact.id!!).setValue(contact).addOnCompleteListener{
            if(it.isSuccessful)
            {
                _result.value = null
            }
            else
            {
                _result.value = it.exception
            }
        }

    }
}

我尝试过将“onActivityCreated”覆盖替换为“onViewCreated”,但没有成功。要么覆盖不起作用,要么我使保存联系人工作的代码不正确。之后,我看到一些帖子说要覆盖“onCreate”和“onAttach”,但当我这样做时,不仅保存联系人不工作,但点击保存联系人现在崩溃了我的应用程序.我不知道如果我这样做不正确,或者如果正确的解决方案是完全通过我,但我会感谢任何帮助.
更新1:我尝试用注解掉的onViewCreated代码初始化viewmodel,虽然它没有崩溃,但保存联系人仍然不起作用。这让我怀疑我是否设置了错误的firebase,因为它不能读/写。

im9ewurl

im9ewurl1#

viewmodel没有初始化。在你的代码中,viewmodel是在onCreatedView中初始化的,但是会出现错误,因为onCreate在生命周期中首先操作。我认为默认创建会更好,因为在创建viewmodel时没有应用额外的选项。

private val viewModel: ContactViewModel by viewModels()
fiei3ece

fiei3ece2#

viewModel.result.observe(viewLifecycleOwner, Observer{
    val message = if (it == null) {
        getString(R.string.added_contact)
    }else{
        getString(R.string.error, it.message)
    }
    Toast.makeText(requireContext(),message,Toast.LENGTH_SHORT).show()
    dismiss()
})

在这里,viewLifecycleOwner必须初始化

相关问题