0

I have a fragment, with only a list view. I am loading the favourites from my database like below. How do I load them async? Currently I am forced to make the async method synchronised while loading the view. I would like it so the view loads, then when the results are ready they are populated so that it is faster. Its not just micro optimisation, I would like to learn how to do this properly.

  public class FavoriteFragment : Fragment
  {
    public event EventHandler<Favorite> FavoriteSelected;

    private FavoriteAdapter _lstAdapter;
    private List<Favorite> _favorites;
    private Repository _repo;

    public override void OnCreate(Bundle savedInstanceState) {
      base.OnCreate(savedInstanceState);
      _repo = TinyIoCContainer.Current.Resolve<Repository>();
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      var view = inflater.Inflate(Resource.Layout.fragment_favorite, container, false);

      var lstFavorites = view.FindViewById<ListView>(Resource.Id.lstFavorites);
      _favorites = Task.Run(async () => await _repo.GetFavoritesAsync()).Result;
      _lstAdapter = new FavoriteAdapter(Activity, _favorites);
      lstFavorites.Adapter = _lstAdapter;
      lstFavorites.ItemClick += (s, e) => FavoriteSelected?.Invoke(this, _favorites[e.Position]);

      return view;
    }
Colton Scottie
  • 807
  • 1
  • 8
  • 22

1 Answers1

0

From this thread onActivityCreated(), you can use OnActivityCreated() to load your data.

 public override async void OnActivityCreated(Bundle savedInstanceState)
{
    base.OnActivityCreated(savedInstanceState);


    await LoadData();
}
private async Task LoadData()
{
 //get data 
}
Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16