App builds but crashes at runtime with a null object reference. Been trying to debug it but can't locate the error but I know that if I remove the setText on the textview which calls a method to retrieve a String that then gets displayed in the MainActivity via a fragment (if I remove this no crash) which leads me to believe that my null object is something to do with how I havent instantiated the viewmodel. Unsure of how to do this.
tried removing and locating bufg from stacktrace which states that the null object reference is in onActivityCreated in the fragment but Dagger generates code this is where I'm lost as if I don't run it builds and shows no compile time error.
public class HomeFragment extends Fragment {
@Inject
HomeViewModel homeViewModel;
TextView tvFrag;
public HomeFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.fragment_home, container, false);
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
tvFrag = getActivity().findViewById(R.id.tv_frag);
tvFrag.setText(homeViewModel.getConnection()); //HERE
}
}
@FragmentScope
public class HomeViewModel extends ViewModel {
private DatabaseService databaseService;
private NetworkService networkService;
private NetworkHelper networkHelper;
@Inject
public HomeViewModel(DatabaseService ds, NetworkService ns, NetworkHelper nh){
this.databaseService = ds;
this.networkService = ns;
this.networkHelper = nh;
}
public String getConnection(){
return "Ben Mohammad Connected";
}
}
GitHub Link - https://github.com/BenMohammad/LearnDagger-STAGE_2-with-dagger-better
Should call the method getConnection() in the viewModel and retrieve a string and display on the fragment which has been added to MainActivity.
Thanks
You haven't performed the dependency injection in that view . It could be :
AndroidSupportInjection.inject(this);
or :
((YourApplicationClass) getActivity().getApplication()).getApplicationComponent().inject(this);
(in case you are not using Dagger for Android ) , in your onCreate
method.
In that case , Dagger will know that it has some dependencies to be injected in that fragment , in your case the HomeViewModel
. Otherwise the HomeViewModel
is still null untill you perform the DI