CodexBloom - Programming Q&A Platform

Unexpected NullPointerException when accessing Fragment arguments in ViewModel with Dagger Hilt

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
android dagger-hilt viewmodel navigation fragment Kotlin

Hey everyone, I'm running into an issue that's driving me crazy. I'm working with a `NullPointerException` in my ViewModel when accessing the arguments passed to my Fragment using Dagger Hilt. I have the following setup: my Fragment is initialized with some arguments, and I'm trying to access these in my ViewModel, but it seems that the arguments are null when the ViewModel is created. In my Fragment, I am using the following code to set up the arguments: ```kotlin class MyFragment : Fragment() { private val args: MyFragmentArgs by navArgs() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_my, container, false) // Initialize ViewModel with Hilt val viewModel: MyViewModel = viewModels() return view } } ``` In my ViewModel, I'm trying to access the arguments like this: ```kotlin @HiltViewModel class MyViewModel @Inject constructor( private val repository: MyRepository ) : ViewModel() { fun someFunction() { val argument = args.someArgument // This line causes NullPointerException // Do something with the argument } } ``` I thought that since I'm using Hilt, the ViewModel should be able to access the arguments defined in the Fragment. However, I am seeing this behavior: ``` java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.MyFragmentArgs.getSomeArgument()' on a null object reference ``` To troubleshoot, I've ensured that the Fragment is correctly passing the arguments in the navigation graph. I've also verified that the arguments are available at the Fragment's lifecycle stage before the ViewModel is accessed. I've tried using a `SavedStateHandle` but it still results in the same scenario. Has anyone faced a similar question or can anyone provide insights on how to properly access Fragment arguments in a ViewModel using Dagger Hilt? I'm working on a web app that needs to handle this. Any ideas what could be causing this?