hamza hamidansari

hamza hamidansari

  • NA
  • 20
  • 12.6k

How to call asynchronus function into a synchronus function?

Oct 8 2018 8:57 AM

I want data from async function in return as a list which will be assign to a list inside synchronus function .I am calling asynchronus function in OnCreateView method of Fragment in xamarin android, which is retur a list . When async method go and fetch data it goes into await mode. When it is waiting for data return it comes out of function and read below code lines of synchronus method where it is called. When async func is not able to return list It is causing empty list on my activity and showing no data.

Here is My Code:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using OSDAMobileModel;  
  6. using System.Net.Http;  
  7. using Newtonsoft.Json;  
  8. using System.Threading.Tasks;  
  9. using System.Collections;  
  10. using Android.App;  
  11. using Android.Content;  
  12. using Android.OS;  
  13. using Android.Runtime;  
  14. using Android.Views;  
  15. using Android.Widget;  
  16. namespace OSDAMobileApp  
  17.  {  
  18. public class CheckInFragment : Fragment  
  19. {  
  20. List lstRoute = new List();  
  21. public override void OnCreate(Bundle savedInstanceState)  
  22. {  
  23. base.OnCreate(savedInstanceState);  
  24. }  
  25. public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)  
  26. {  
  27. var view = inflater.Inflate(Resource.Layout.SelectRoute, container, false);  
  28. ListView routesListView = view.FindViewById(Resource.Id.ListView);  
  29. List routeslst = lstRoute;  
  30. OnAppearing();  
  31. routesListView.Adapter = new CustomListAdapter(lstRoute);  
  32. return view;  
  33. }  
  34. protected async Task> OnAppearing() //protected List OnAppearing()  
  35. {  
  36. SetupFiles setupFiles = new SetupFiles();  
  37. //PRPMaster prpMaster = new PRPMaster();  
  38. var prpDetails = await setupFiles.LoadTextAsync("PRPDetails.txt");  
  39. PRPMaster prpMaster = JsonConvert.DeserializeObject(prpDetails);  
  40. foreach (var item in prpMaster.PRPDetails)  
  41. {  
  42. lstRoute.Add(item.Route);  
  43. }  
  44. return lstRoute;  
  45. }  
  46. }  
  47. }  

Answers (1)