Я использовал компонент навигации в своем приложении. в одном из моих фрагментов (назовем его FragmentA) у меня много полей. и в этом фрагменте я определяю группу радиосвязи для видимых / исчезнувших в некоторых полях. все работает отлично, когда я перешел из HomeFragment во FragmentA, но когда я go из FragmentA в другое место назначения, которое тоже является фрагментом (и давайте назовем его, например, FragmentB) и обработал все это с помощью компонента навигации, а затем попытался снова FragmentA, я получил нулевой указатель для группы просмотра как unknown Source
с этим сообщением: Parameter specified as non-null is null
. и это мой код для обработки полей Visible / Gone.
private fun showChildren(v: View, isShow: Boolean) {
val viewGroup = v as ViewGroup
for (i in 0 until viewGroup.childCount) {
val v1 = viewGroup.getChildAt(i)
(v1 as? ViewGroup)?.let { showChildren(it, isShow) }
if (v1.tag == "check_for_visibility" && isShow) {
v1.visibility = View.VISIBLE
} else if (v1.tag == "check_for_visibility" && !isShow) {
v1.visibility = View.GONE
}
}
}
, пожалуйста, расскажите мне, как я могу обработать это исключение нулевого указателя с помощью ViewGroup при возвращении из FragmentB в FragmentA?
edit:
import android.content.Intent
import android.speech.RecognizerIntent
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.AdapterView.OnItemSelectedListener
import android.widget.ArrayAdapter
import androidx.core.content.ContextCompat
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
class AddPickupContinuousParentFragment :
BaseFragment<FragmentAddPickupContinuousParentBinding, AddPickupContinuousParentViewModel>(
R.layout.fragment_add_pickup_continuous_parent,
AddPickupContinuousParentViewModel()
) {
private var kindOfRentList: ArrayList<String> = arrayListOf()
private var selectedRent = ""
override fun initVariables() {
binding.addPickupContinuousParentViewModel = vModel
}
override fun initObserves() {
}
override fun initViews() {
val receivedWaybill =
arguments?.let { AddPickupContinuousParentFragmentArgs.fromBundle(it).waybill }
val receivedClosedArray =
arguments?.let { AddPickupContinuousParentFragmentArgs.fromBundle(it).closedArray }
if (receivedWaybill != null && receivedWaybill != "0") {
if (receivedWaybill.isNotEmpty()) {
binding.layoutCargo.etNewPickupWaybill.isEnabled = false
binding.layoutCargo.etNewPickupWaybill.setText(receivedWaybill)
}
}
if (receivedClosedArray != null) {
if (receivedClosedArray.isNotEmpty()) {
binding.layoutCargo.etNewPickupClosedCount.isEnabled = false
binding.layoutCargo.etNewPickupClosedCount.setText(receivedClosedArray.size.toString())
}
}
val countries: Array<out String> = resources.getStringArray(R.array.countries_array)
ArrayAdapter(
requireContext(),
android.R.layout.simple_list_item_1,
countries
).also {
binding.layoutSender.autoAddSenderStateCity.setAdapter(it)
binding.layoutReceiver.autoAddReceiverStateCity.setAdapter(it)
// spinner init
kindOfRentList.add("test1")
kindOfRentList.add("test2")
val kindOfRentAdapter =
ArrayAdapter(requireContext(), android.R.layout.simple_spinner_item, kindOfRentList)
kindOfRentAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
binding.layoutCargo.spinnerNewPickupKindRent.adapter =
kindOfRentAdapter
selectedRent = kindOfRentList[0]
binding.layoutCargo.spinnerNewPickupKindRent.onItemSelectedListener =
object : OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>,
view: View,
position: Int,
id: Long
) {
selectedRent =
binding.layoutCargo.spinnerNewPickupKindRent.selectedItem.toString()
}
override fun onNothingSelected(parent: AdapterView<*>?) {}
}
// visible or gone fields
vModel.editTextVisibility.observe(
viewLifecycleOwner,
Observer {
if (it == true) {
binding.radioNewPickupNo.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.red
)
)
binding.radioNewPickupYes.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightGray
)
)
activity?.window?.decorView?.let { it1 ->
showChildren(it1, true)
}
} else {
binding.radioNewPickupNo.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.lightGray
)
)
binding.radioNewPickupYes.setTextColor(
ContextCompat.getColor(
requireContext(),
R.color.green
)
)
activity?.window?.decorView?.let { it1 -> showChildren(it1, false) }
}
})
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH)
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "fa");
binding.layoutSender.imgAddSenderName.setOnClickListener {
startActivityForResult(intent, 700)
}
binding.layoutSender.imgAddSenderAddress.setOnClickListener {
startActivityForResult(intent, 701)
}
binding.layoutSender.imgAddSenderCompany.setOnClickListener {
startActivityForResult(intent, 702)
}
binding.layoutReceiver.imgAddReceiverName.setOnClickListener {
startActivityForResult(intent, 703)
}
binding.layoutReceiver.imgAddReceiverAddress.setOnClickListener {
startActivityForResult(intent, 704)
}
binding.layoutReceiver.imgAddReceiverCompany.setOnClickListener {
startActivityForResult(intent, 705)
}
binding.btnAddPickupRegister.setOnClickListener {
findNavController().navigate(R.id.action_addPickupContinuousParentFragment_to_finalizeCargoFragment)
}
}
override fun onActivityResult(
requestCode: Int,
resultCode: Int,
data: Intent?
) {
when (requestCode) {
700 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderName.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
701 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderAddress.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
702 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutSender.etAddSenderCompany.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
703 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverName.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
704 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverAddress.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
705 -> {
try {
if (data != null) {
val result: String? = data.getStringArrayListExtra(
RecognizerIntent.EXTRA_RESULTS
)[0]
binding.layoutReceiver.etAddReceiverCompany.setText(result)
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
private fun showChildren(v: View, isShow: Boolean) {
try {
val viewGroup = v as ViewGroup
for (i in 0 until viewGroup.childCount) {
val v1 = viewGroup.getChildAt(i)
(v1 as? ViewGroup)?.let { showChildren(it, isShow) }
if (v1.tag == "check_for_visibility" && isShow) {
v1.visibility = View.VISIBLE
} else if (v1.tag == "check_for_visibility" && !isShow) {
v1.visibility = View.GONE
}
}
} catch (e: Exception) {
e.printStackTrace()
}
}
}