我有一个从数据库获取数据的异步Web服务。我能够很好地返回数据,但似乎问题是应用程序正在向适配器发送列表(此时为空),然后返回null异常。
protected override void OnCreate(Bundle savedInstanceState)
{
// Create your application here
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.HerdDetailsLayout);
this.GetData();
List = FindViewById<ListView>(Resource.Id.Details);
this.updateAdapter();
List.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) =>
{
var listView = sender as ListView;
Data item = data.List[e.Position];
};
}
private async void GetData(){
HerdsRESTFulService herdService = new HerdsRESTFulService();
herds = await herdService.GetAllAsync();
Console.WriteLine("Hello");
}
public void updateAdapter()
{
adapter = new HerdListAdapter(this, herds);
RunOnUiThread(() => adapter.NotifyDataSetChanged());
herdList.Adapter = adapter;
}
....
public async Task<Data> GetAllAsync()
{
dynamic responseString = await "http://foobar"
.WithHeader("Authorization", "Bearer numbers")
.WithHeader("Accept", "application/json")
.GetAsync().ReceiveString();
}
如何在将异步放入适配器之前等待异步完成?
出现错误的地方:
public ListAdapter(Activity context, Data data) : base()
{
this.context = context;
this.data = data; // Null here because the async didn't finish on time before the adapter was set.
}
答案 0 :(得分:0)
你无法等待无效的方法,所以GetData()
就是&#34;一劳永逸的&#34;意味着执行将开始,然后代码立即移动到下一条指令。这就是updateAdapter()
在GetData()
完成之前发生的原因。
将其更改为返回任务,然后等待通话:
private async Task GetData()
{
HerdsRESTFulService herdService = new HerdsRESTFulService();
herds = await herdService.GetAllAsync();
Console.WriteLine("Hello");
}
然后:
....
await this.updateAdapter();
...
或许更好的是在等待时做一些工作:
Task dataTask = this.GetData();
List = FindViewById<ListView>(Resource.Id.Details);
await dataTask;
this.updateAdapter();