我正在使用Android Studio我需要从API http://mindicador.cl/api检索所有数据,我需要获取四个对象:“uf”,“dolar”,“euro”和“utm”。实际上我已经可以检索它,当我想将它添加到数组时问题就出现了,因为将来我想处理这个数组以便在RecyclerView上显示它们。
public class MainActivity extends AppCompatActivity {
private List<IEconomicoObject> iEconomicoObjects;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iEconomicoObjects = new ArrayList<>();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MiIndicadorAPI.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
MiIndicadorAPI api = retrofit.create(MiIndicadorAPI.class);
final Call<IEconomicoAPI> iEconomicoAPICall = api.getAPI();
iEconomicoAPICall.enqueue(new Callback<IEconomicoAPI>() {
@Override
public void onResponse(Call<IEconomicoAPI> call, Response<IEconomicoAPI> response) {
iEconomicoObjects.add(response.body().getUf());
iEconomicoObjects.add(response.body().getUtm());
iEconomicoObjects.add(response.body().getEuro());
iEconomicoObjects.add(response.body().getDolar());
}
@Override
public void onFailure(Call<IEconomicoAPI> call, Throwable t) {
Log.e("onFailure", "" + t.getMessage());
}
});
// here is the problem, the list is empty and should be show the data added it previously
if (!iEconomicoObjects.isEmpty()) {
for (IEconomicoObject o: iEconomicoObjects) {
Log.e("info", "nombre: " + o.getNombre());
}
} else {
Log.e("info", "the list is empty");
}
}
}
答案 0 :(得分:2)
列表在您尝试阅读时将显示为空。由于改进返回会导致与UIThread并行调用的回调,因此您应该在回调内读取列表。