解析c#中异步检索数据的方法,如何访问数据
本文关键字:数据 何访问 访问 方法 异步 检索 解析 | 更新日期: 2023-09-27 18:12:33
我试图检索一个简单的查询解析和添加自定义适配器上的内容,但我可以弄清楚它是如何,我从文档中看到,只有与异步我可以得到数据,但我怎么能添加数据后到适配器,如果异步方法总是返回空?这是我正在尝试的,但不工作
public class BusinessListFragment : Fragment
{
private List<Business> _list;
ListView businessListView;
public async override void OnResume()
{
base.OnResume();
_list = await GetData();
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.BusinessList, container, false);
businessListView = view.FindViewById<ListView>(Resource.Id.businessListView);
var adapter = new BusinessListAdapter(Activity, _list);
businessListView.Adapter = adapter;
adapter.NotifyDataSetChanged ();
return view;
}
public async Task<List<Business>> GetData(){
var query = ParseObject.GetQuery("Business");
IEnumerable<ParseObject> results = await query.FindAsync();
var data = new List<Business>();
foreach (var temp in results)
{
var _business = new Business();
// This does not require a network access.
_business.Name = temp.Get<string>("name");
_business.Address = temp.Get<string>("address");
_business.Town = temp.Get<string>("town");
_business.Country = temp.Get<string>("country");
data.Add (_business);
}
return data;
}
}
我做错了什么?应该是非常简单的
你通常不需要使用async和await的显式任务方法——它们被引入c#是专门为了简化这类问题。
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.BusinessList, container, false);
businessListView = view.FindViewById<ListView>(Resource.Id.businessListView);
_list = await GetData();
var adapter = new BusinessListAdapter(Activity, _list);
businessListView.Adapter = adapter;
adapter.NotifyDataSetChanged ();
return view;
}
public async Task<List<Business>> GetData(){
var query = ParseObject.GetQuery("Business");
IEnumerable<ParseObject> results = await query.FindAsync();
var data = new List<Business>();
foreach (var temp in results)
{
var _business = new Business();
// This does not require a network access.
_business.Name = temp.Get<string>("name");
_business.Address = temp.Get<string>("address");
_business.Town = temp.Get<string>("town");
_business.Country = temp.Get<string>("country");
data.Add (_business);
}
return data;
}
事实证明,我不必返回数据,我可以用这种方式在我的GetData()方法中重新创建并填充适配器:
Activity.RunOnUiThread(() =>{
var adapter = new BusinessListAdapter(Activity, data);
businessListView.Adapter = adapter;
adapter.NotifyDataSetChanged();
Console.WriteLine ("name="+data.Count.ToString());
});
谢谢大家的帮助