I have a fragment that I use to return a list of articles received from a REST API. The REST API is async
and I use await
to wait for it to complete. When completed, I pass the data (that is List<Article>
) to a variable called listofarticles
and use it to create an ArrayAdapter
.
I do the above code in OnCreate
method of this fragment that's supposed to run before the OnCreateView
as far as I know.
My code works in an activity but not a fragment.
Problem: The call to awaitable REST method is not awaited.
When debugging line by line it goes like this:
OnCreate
is called. Processed to the line where I call the awaitable method (that is supposed to filllistofarticles
) and simply skips to theOnCreateView
. Thereforelistofarticles
is null.OnCreateView
is called and processed. At this point program just goes back to the activity it's called.I can no longer debug it because Xamarin Studio thinks I'm finished but at the emulator it just starts to call the REST method after all this and because of that the data inside
listofarticles
is useless because I can't pass it to Adapter now.
Why is this happening and how to fix it??
public class LatestNewsFragment : Android.Support.V4.App.Fragment, ListView.IOnItemClickListener
{
private Context globalContext = null;
private List<Article> listofarticles;
private ArrayAdapter<Article> listAdapter;
public LatestNewsFragment()
{
this.RetainInstance = true;
}
public async override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
globalContext = this.Context;
//Create a progress dialog for loading
ProgressDialog pr = new ProgressDialog(globalContext);
pr.SetMessage("Loading data");
pr.SetCancelable(false);
var rest = new RestAccess();
pr.Show();
//Download the data from the REST API
listofarticles = await rest.ListArticlesAsync ("SomeSource");
pr.Hide();
Console.WriteLine (listofarticles.Capacity);
listAdapter = new ArrayAdapter<Article>(globalContext, Android.Resource.Layout.SimpleListItem1, listofarticles);
}
public override View OnCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var view = inflater.Inflate(Resource.Layout.Fragment_LatestNews, null);
ListView listView = view.FindViewById<ListView>(Resource.Id.list_latestnews);
listView.Adapter = listAdapter;
listView.OnItemClickListener = this;
return view;
}
}