我遇到了以下错误:
我正在使用Android架构组件,尝试实例化ViewModel并从LiveData观察数据。但是我卡在这里,请帮助我解决这个问题:
Attempt to invoke virtual method 'void android.arch.lifecycle.LiveData.observe(android.arch.lifecycle.LifecycleOwner, android.arch.lifecycle.Observer)' on a null object reference
我的Fragment是这样的: 当调用getCompany()方法时,我会遇到空指针异常错误。
public class CompanyFragment extends LifecycleFragment {
private CompanyViewModel companyViewModel;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
companyViewModel = ViewModelProviders.of(this).get(CompanyViewModel.class);
companyViewModel.initData();
companyViewModel.getCompany().observe(this, new Observer<CompanyEntity>() {
@Override
public void onChanged(@Nullable CompanyEntity companyEntity) {
}
});
}
@Override
public View onCreateView(LayoutInflater inflater,
@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_company, container, false);
}
}
我的ViewModel类是这样的:
public class CompanyViewModel extends ViewModel {
private LiveData<CompanyEntity> companyEntityLiveData;
private CompanyRepository companyRepo;
public CompanyViewModel() {}
public CompanyViewModel(CompanyRepository companyRepo){
this.companyRepo = companyRepo;
}
public void initData(){
companyEntityLiveData = companyRepo.getCompany();
}
public LiveData<CompanyEntity> getCompany() {
return companyEntityLiveData;
}
}
错误出现在这一行:
companyViewModel.getCompany().observe(this, new Observer<CompanyEntity>() {
@Override
public void onChanged(@Nullable CompanyEntity companyEntity) {
}
});
这是我的CompanyRepository类:
public class CompanyRepository {
private WebService webService;
public CompanyRepository(){
}
public LiveData<CompanyEntity> getCompany() {
final MutableLiveData<CompanyEntity> data = new MutableLiveData<>();
webService.getCompany().enqueue(new Callback<CompanyEntity>() {
@Override
public void onResponse(Call<CompanyEntity> call, Response<CompanyEntity> response) {
data.setValue(response.body());
}
@Override
public void onFailure(Call<CompanyEntity> call, Throwable t) {
}
});
return data;
}
}
companyRepo.getCompany()
的代码,因此不知道为什么它可能会返回null
。您可以编辑您的问题并发布CompanyRepository
的代码。 - CommonsWareinitData()
和getCompany()
调用,看看发生了什么。 - CommonsWare