progrAmmar
progrAmmar

Reputation: 2670

Xamarin.Android: Async Task throws unhandled exception

I have a Xamarin Android application where I am getting data from a web service and then binding it to the list view.

The method in MainActivity.cs is the following:

private async Task LoadDataFromService()
{

    int userId = int.Parse(applicationData[USER_ID]); // Shared prefrenced data

    //ASYNC Method getting data from JSON and converting it into Sales Object
    Task<IList<Sales>> apiDataTask = UserData.GetSales(userId); 
    IList<Sales> apiData = await apiDataTask;
    if (apiData != null)
    {
        salesList = apiData as List<Sales>; 
        dbManager.Update(salesList); //Sync with SQLite DB

    }
}

In my MainActivity I have defined a global variable which gives this task an identifier

public class MainActivity : Activity
{
    private Task loadData;
}

And I am calling this as follows:

public class MainActivity : Activity
{
    private Task loadData;
    protected override void OnCreate(Bundle bundle)
    { 
        loadData = new Task(async () => { await LoadDataFromService(); });
    }
}

Then I have to wait till the data is downloaded and then I put the data in ListView.

protected override void OnStart()
{
     base.OnStart();
     loadData.Start(); // This is causing to generate an exception
     loadData.ContinueWith(t => { BindData(); }).Wait();
 }

The only issue I am getting is that it ends in an unhanled exception the message saying An unhandled exception occured. , the message comes after OnStart has fired and there is no indication as to what the issue may be.

Upvotes: 0

Views: 543

Answers (1)

Sebi
Sebi

Reputation: 3979

I'm not sure what causes your Exception, because this Message is very poor. But I found an issue which you should fix and which maybe is enough to make your code running. In the OnStart() Method you are using .Wait();. This can cause a deadlock and will block your UI. Read more about here. Further I think you don't need to store your Task. You can await it in OnStart().

So I would recommend you following OnStart();:

protected override async void OnStart()
{
     base.OnStart();

     var data = await LoadDataFromService();
     BindingData();    
 }

Further it's convention that all async methods are named with Async as ending. Maybe this can help you. If this doesn't solve your issue please try to figure out the inner-Exception. Just debug over your Exception and choose the Property "InnerException" to see it.

Upvotes: 1

Related Questions