0

I am a beginner in Xamarin development and I just tried Xamarin.Forms to Develop Android & iOS App with shared Code, and what I'm trying to do here is to get data from API with Plugin.RestClient NuGet package.

Here is the MainViewModel. '''

    public MainViewModel()
    {
        InitializeDataAsync();
    }

    private async Task InitializeDataAsync()
    {
        var vehicleServices = new VehicleServices();

        VehicleList = await vehicleServices.GetVehiclesAsync();
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

''' The services '''

    public async Task<List<Vehicle>> GetVehiclesAsync()
    {

        RestClient<Vehicle> restClient = new RestClient<Vehicle>();

        var vehicleList = await restClient.GetAsync();

        return vehicleList;

    }

''' And RestClient '''

   private const string WebServiceUrl = "https://localhost:44355/api/Vehicles";

    public async Task<List<T>> GetAsync()
    {
        ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
        var httpClient = new HttpClient();

        var json = await httpClient.GetStringAsync(WebServiceUrl);

        var vehicles = JsonConvert.DeserializeObject<List<T>>(json);

        return vehicles;
    }

''' I can see my Debug for the url and json response. But on my Android Emulator there is nothing on the list. I also already add internet permission on my Android Manifest. Anyone have ideas on what to do?

  • you are calling an async method from a constructor without using await – Jason Nov 05 '21 at 11:38
  • Does this answer your question? [C# async and await not waiting for code to finish](https://stackoverflow.com/questions/35280808/c-sharp-async-and-await-not-waiting-for-code-to-finish). The accepted answer there explains that what you have done, means the constructor exits (allowing the calling code to continue), so your page gets displayed, **before** `await vehicleServices.GetVehiclesAsync` finishes its work. That is why the list is empty. Did the compiler give you a warning on line `InitializeDataAsync();`? – ToolmakerSteve Nov 05 '21 at 23:27
  • See also https://stackoverflow.com/questions/23048285/call-asynchronous-method-in-constructor. Follow the link in Cleary's answer, to the page where he describes "Factory Pattern". That's a clean way to get the async task completed. – ToolmakerSteve Nov 05 '21 at 23:33

0 Answers0