我有这种方法:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AnimalWebService animalWebService = restAdapter.create(AnimalWebService.class);
Callback<List<Animal>> callback = new Callback<List<Animal>>() {
@Override
public void success(List<Animal> animals, Response response) {
if (animals == null) {
Context context = getApplicationContext();
CharSequence text = "No animals available!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else {
ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals);
}
}
@Override
public void failure(RetrofitError retrofitError) {
return;
}
};
animalWebService.get(callback);
theListView.setAdapter(theAdapter);
}
最后,我有
theListView.setAdapter(theAdapter);
,但是在这里无法识别theAdapter
,因为它是在内部类中声明的。我该如何解决?在Android中进行编程时,针对这种情况的最佳做法是什么?
最佳答案
如果您不需要在Activity类的其他部分中引用theAdapter
,则只需从回调中对其进行更新:
Callback<List<Animal>> callback = new Callback<List<Animal>>() {
@Override
public void success(List<Animal> animals, Response response) {
if (animals == null) {
}
else {
ListAdapter theAdapter = new MyAdapter(getApplicationContext(), animals);
theListView.setAdapter(theAdapter);
}
}
@Override
public void failure(RetrofitError retrofitError) {
return;
}
};
这样可以确保您永远不会在列表视图上调用
setAdapter(null)
,这很好。您应该根据回调的结果触发事件:您的调用可能会失败(然后调用failure
),或者可能返回一个空列表。在这些情况下,我们不希望将ListView附加到适配器。