应用程序构建但在运行时使用空对象引用崩溃。试图调试但无法找到错误,但我知道如果我删除textview上的setText,它调用一个方法来检索一个String,然后通过一个片段显示在MainActivity中(如果我删除它没有崩溃)这让我相信我的null对象与我没有实例化viewmodel有关。不确定如何做到这一点。
尝试从stacktrace中删除和定位bufg,它声明空对象引用在片段中的onActivityCreated中,但是Dagger生成代码,这就是我丢失的地方,好像我没有运行它构建并且没有显示编译时错误。
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链接 - https://github.com/BenMohammad/LearnDagger-STAGE_2-with-dagger-better
应该在viewModel中调用方法getConnection()并检索字符串并显示已添加到MainActivity的片段。
谢谢
您尚未在该视图中执行依赖项注入。它可能是 :
AndroidSupportInjection.inject(this);
要么 :
((YourApplicationClass) getActivity().getApplication()).getApplicationComponent().inject(this);
(如果您没有使用Dagger for Android),请使用onCreate
方法。
在这种情况下,Dagger会知道它有一些依赖注入该片段,在你的情况下是HomeViewModel
。否则HomeViewModel
仍为空,直到您执行DI
你没有在你的片段中注入HomeViewModel
。尝试在你的AndroidSupportInjection.inject(this);
方法中使用onCreate
。方法应该是这样的
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidSupportInjection.inject(this);
}
好吧,我认为答案(包括我的答案)比你更困惑。
必须像这样初始化ViewModel(我不知道你的模块中有什么,但这是正确的方法):在onCreate
方法中去:
HomeViewModel homeviewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
如果需要将依赖项传递给viewmodel,请使用ViewModel Factory。谷歌自己或只是参考this link
您试图在父活动中找到tv_frag
而不是当前片段。
改成:
tvFrag = getView().findViewById(R.id.tv_frag);
tvFrag.setText(homeViewModel.getConnection());