Calling REST Service inside the fragment and populating data inside the recycle view

KhawajaMujtabaKhawajaMujtaba GBMember
edited April 2016 in Xamarin.Android

Hi!

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!

Answers

Sign In or Register to comment.