android-fragments 尝试对空对象引用调用虚拟方法“void android.arch.lifecycle.LiveData.observe”

kmbjn2e3  于 2022-11-14  发布在  Android
关注(0)|答案(5)|浏览(154)

我收到以下错误
我正在使用Android架构组件,并试图示例化视图模型和观察数据从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

我的片段是这样的:调用getCompany()方法时,发生获取和NullPoint异常错误

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;
    }
}
wsewodh2

wsewodh21#

CompanyRepository类中,每次访问公司时都会创建一个新的LiveData示例,这意味着您的Activity会观察到一个旧示例。
getCompany方法应更改为始终返回相同的LiveData示例。此外,您还应将setValue()更改为postValue(),因为您正尝试在后台线程上更新该值。

final MutableLiveData<CompanyEntity> data = new MutableLiveData<>();
public LiveData<CompanyEntity> getCompany() {

    webService.getCompany().enqueue(new Callback<CompanyEntity>() {
        @Override
        public void onResponse(Call<CompanyEntity> call, Response<CompanyEntity> response) {
            data.postValue(response.body());
        }

        @Override
        public void onFailure(Call<CompanyEntity> call, Throwable t) {

        }
    });

    return data;
}
pvabu6sv

pvabu6sv2#

也许你可以在方法之后声明一个LiveData对象。
我的情况就是这样。

fun aMethod() {
    _aLiveData.value = Unit
}

private val _aLiveData = MutableLiveData<Unit>()
val aLiveData: LiveData<Unit> = _aLiveData

事实上,它应该是这样的。

private val _aLiveData = MutableLiveData<Unit>()
val aLiveData: LiveData<Unit> = _aLiveData

fun aMethod() {
    _aLiveData.value = Unit
}
g52tjvyc

g52tjvyc3#

变更

public CompanyViewModel(){
    companyRepo= new companyRepo();
}

public LiveData<CompanyEntity> getCompany() {
    if(companyEntityLiveData==null)
        companyEntityLiveData= companyRepo.getSection();
    return companyEntityLiveData;
}

在你的片段中:

CompanyViewModel companyViewModel= 
    ViewModelProviders.of(this).get(CompanyViewModel .class);
    LiveData<CompanyEntity> s = companyViewModel.getCompany();

    s.observe(this, new Observer<CompanyEntity>() {
        @Override
        public void onChanged(@Nullable CompanyEntity companyEntity) {
            Toast.makeText(getContext(),"Go go go", Toast.LENGTH_LONG).show();
        }
    });
az31mfrm

az31mfrm4#

在getCompany方法中需要检查companyEntityLiveData对象是否为null,如果是则调用其中的服务。

public LiveData<CompanyEntity> getCompany() {
    if(companyEntityLiveData == null){
       companyEntityLiveData = companyRepo.getCompany();
    }
    return companyEntityLiveData;
}
kqqjbcuj

kqqjbcuj5#

问题是您尝试使用的是尚未初始化的内容。因此,为了不依赖于执行顺序,我们必须在存储存储库返回内容的变量中建立安全的可空性private val nullableObj: LiveData<T2>?
这样,我们甚至可以在仓库加载属性之前使用它。

val aUse: LiveData<T> = MediatorLiveData<T>().apply {
    nullableObj?.let {
    }
}
private val nullableObj: LiveData<T2>? = repository::getNullableObj

在使用Repository #getCompany()之前回答你的问题,检查是否为空。

companyVM.company?.observe(...) { ... }

GL语言

相关问题