我是Xamarin Android的初学者。我正在尝试构建一个使用REST服务从服务器获取数据的应用程序。
我试图在片段中调用Web服务,该片段使用回收站视图列出数据的内容。问题是,在调用回收器适配器类之后才进行对客户端函数的调用,这样就不会填充数据。
这是我的片段类的代码:
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
notifications = new List<Notification_Struct>();
mClient = new WebClient();
Url = new Uri("http://10.71.34.1:63026/api/notifications/PetePentreath");
mClient.DownloadDataAsync(Url);
mClient.DownloadDataCompleted+= MClient_DownloadDataCompleted;
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
// return inflater.Inflate(Resource.Layout.YourFragment, container, false);
View view = inflater.Inflate(Resource.Layout.recyclerviewcontainer, container, false);
notifitem = view.FindViewById<RecyclerView>(Resource.Id.rv);
notifitem.HasFixedSize = true;
layoutmanager = new LinearLayoutManager(Activity);
adapter = new NotificationAdapter(notifications);
notifitem.SetLayoutManager(layoutmanager);
notifitem.SetAdapter(adapter);
return view;
}
void MClient_DownloadDataCompleted (object sender, DownloadDataCompletedEventArgs e)
{
string json = Encoding.UTF8.GetString(e.Result);
notifications = JsonConvert.DeserializeObject<List<Notification_Struct>>(json);
}
}
我在OnCreate内部调用Web服务,因为在OnCreateView内部调用它不会触发DownloadDataCompleted事件。
我希望在调用适配器类之前触发此事件,以便通知变量具有要传递给回收者视图适配器的数据。我该如何实现?
任何帮助表示赞赏。
谢谢!
最佳答案
简而言之:
您需要等待请求完成,或者需要在请求完成后重置适配器。我建议阅读async/await
:https://github.com/xamarin/mobile-samples/tree/master/AsyncAwait
即
void MClient_DownloadDataCompleted (object sender, DownloadDataCompletedEventArgs e)
{
string json = Encoding.UTF8.GetString(e.Result);
notifications = JsonConvert.DeserializeObject<List<Notification_Struct>>(json);
//Get a reference to your RecyclerView
//Set the adapter with your notifications
recyclerView = (RecyclerView) FindViewById(R.id.myRecyclerView); //Or keep a reference from before
adapter = new NotificationAdapter(notifications);
recyclerView.setAdapter(adapter);
}