I am currently developing an Android NFC application. This application contains a NavigationDrawer in which I can access 3 different fragments which each correspond to 3 different NFC features.
My goal is that when the onNewIntent method is called, so when the NFC tag is detected, I update the UI with the information in the tag.
Because of the navController, I can’t use the supportFragmentManager.findFragmentById
method directly, otherwise I would get a NullPointerException
. So I tried to use the navController.currentDestination
method but the value returned is null too. What can I do?
updateUI() method in MainActivity class:
private fun updateUI() {
val navController = findNavController(R.id.nav_host_fragment)
val fragment = navController.currentDestination as? MemoryFragment
fragment?.setManufacturerValue((nfcManufacturer.getValue(tag!!.id[6].toInt())))
}
MemoryFragment class:
class MemoryFragment : Fragment() {
private lateinit var memoryViewModel: MemoryViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
memoryViewModel = ViewModelProvider(this).get(MemoryViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_memory, container, false)
val icManuf: TextView = root.findViewById(R.id.ic_manufacturer_value)
memoryViewModel.icManufacturer.observe(viewLifecycleOwner, Observer {
icManuf.text = it
})
return root
}
fun setManufacturerValue(icManufacturer: String) {
memoryViewModel.setManufacturer(icManufacturer)
}
}
MemoryViewModel class:
class MemoryViewModel : ViewModel() {
// The current IC Manufacturer
private val _icManufacturer = MutableLiveData<String>()
val icManufacturer: LiveData<String>
get() = _icManufacturer
init {
_icManufacturer.value = ""
}
fun setManufacturer(value: String) {
_icManufacturer.value = value
}
}