I'm a beginner with Xamarin Android. I'm trying to build an app that uses a REST service to get data from the server. I'm trying to call the web service inside a fragment which uses a recycler view to list the contents of the data. The issue is, the call to the client function is made after the recycler adapter class has been called so the data doesn't get populated.
Here's the code of my fragment class:
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);
}
}
I'm calling the web service inside OnCreate because calling it inside OnCreateView doesn't fire up the DownloadDataCompleted event. I want this event to be fired before the adapter class is called so the notification variable has the data to be passed to the recycler view adapter. How do I achieve this?
Any help is appreciated.
Thanks!
答案 0 :(得分:2)
简而言之:
您需要等待您的请求完成,或者您需要在请求完成后重置适配器。我建议您阅读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);
}