android - Retrofit 在使用 LiveData 时提供 onFailure 回调 - 无法在没有参数的情况下调用 public androidx.lifecycle.LiveData()
问题描述
I/System.out: Failure -> Failed to invoke public androidx.lifecycle.LiveData() with no args
我正在从 API 获取数据。我正在尝试使用 MVVM,我是 MVVM 的新手。所以我从 ViewModel 调用 api 并在方法中返回数据。我正在从我的 MainActivity 中观察该方法。但我不知道为什么会给我以下错误。
改造进入失败回调。但是当我不使用 LiveData 时,它正在成功回调中。
I/System.out: Failure -> Failed to invoke public androidx.lifecycle.LiveData() with no args
我的视图模型
public class MainViewModel extends ViewModel {
private ApiInterface apiInterface;
private LiveData < List < Feature >> featuresList;
public MainViewModel() {
apiInterface = ApiClient.getClient().create(ApiInterface.class);
getEqData();
featuresList = new MutableLiveData < > ();
}
public void getEqData() {
apiInterface.getTodos().enqueue(new Callback < EarthquakeData > () {
@Override
public void onResponse(Call < EarthquakeData > call, Response < EarthquakeData > response) {
featuresList = response.body().features;
}
@Override
public void onFailure(Call < EarthquakeData > call, Throwable t) {
System.out.println("Failure -> " + t.getMessage());
}
});
}
public LiveData < List < Feature >> returnEqData() {
return featuresList;
}
}
主要活动
public class MainActivity extends AppCompatActivity {
private static final String TAG = "sagar";
private MainViewModel mainViewModel;
private RecyclerView rvEarthquake;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rvEarthquake = findViewById(R.id.rvEarthquake);
EarthquakeAdapter adapter = new EarthquakeAdapter(this);
rvEarthquake.setLayoutManager(new LinearLayoutManager(this));
rvEarthquake.setAdapter(adapter);
mainViewModel = ViewModelProviders.of(this).get(MainViewModel.class);
mainViewModel.returnEqData().observe(this, new Observer < List < Feature >> () {
@Override
public void onChanged(List < Feature > features) {
adapter.setData(features);
}
});
}
}
解决方案
使用 setValue 或 postValue 在 featuresList 中设置值,如下所示
featuresList.setValue(response.body().features);
推荐阅读
- methods - 如何在 setFormula() 方法中的函数引用中进行相对单元格引用?
- java - 将对象访问限制为Java中的一个线程
- spring-boot - 如何检查哪个 Spring Boot 版本与 spring-cloud-gcp-starter-data-spanner 1.1.0.RC1 一起使用?
- python - 将一列中的浮点值与 pandas DataFrame 中的所有其他列进行比较
- python - 重用 aiosqlite 连接
- python - 如何在 sklearn 中修复这个自定义转换器?
- html - 创建一组内联 div,它们扩展其宽度以填充其父级 - 但在达到其最小宽度时也会中断以形成新行
- vuejs2 - 如何使用
,谁能给我一个示例演示? - image - 如何输出层叠图像或堆叠图像
- javascript - 事件处理程序/侦听器对 Javascript/Html 无响应