Hypixus
Hypixus

Reputation: 61

Asynchronous functions in Xamarin C# Android - Application stuck with thread

I'm trying to figure out a bug in my C# Xamarin Android code. Simple thing this application is ought to do - connect to the REST API, download the contents as a string for further analysis. At first my mistake was not including async tasks and using voids instead, but when I changed them the code seems to be stuck at point of retrieval of data.

String content;
private void OnClick1(object sender, EventArgs e)
{
    output.Text = "";
    GetJSONTextFromWeb("https://ameobea.me/osutrack/api/get_changes.php?user=XXXXXX&mode=0", "XXXXXX", "0");
    while (content==null)
    {
        DoNothing();
    }
    output.Text = content;
}
private async Task GetJSONTextFromWeb(String address, String user, String modeID)
   {
      URL url = new URL(address);
      URLConnection conn = url.OpenConnection();
      //conn.AddRequestProperty("user", user);   those lines are
      //conn.AddRequestProperty("mode", modeID); removed for investigation.
      //conn.Connect(); //this one caused the same issue.
      content = (String)conn.Content; //Here the code seems to freeze without any warning.
   }
private void DoNothing()
{
   //literally. Made to await for the result.
}

Anyone knows the possible reason?

Upvotes: 1

Views: 71

Answers (1)

JoeTomks
JoeTomks

Reputation: 3276

I'd suggest swapping out the use of that particular library in favor of the System.Http assembly, it's supported in Xamarin and is a lot better documented. I'd change your above code to something like below (Don't forget to declare System.Net.Http in the same place that you've declared your other assemblies).

using System.Net.Http;    

async private void OnClick1(object sender, EventArgs e)
{ 
    output.Text = "";
    // await the return of a string from the url address
    // awaiting this removes the need for the pointless while loop you were doing
    content = await GetJSONTextFromWeb("https://ameobea.me/osutrack/api/get_changes.php?user=XXXXXX&mode=0");
    output.Text = content;
}

private async Task<string> GetJSONTextFromWeb(String address)
{
    // The library you were using is a poorly documented port from a JAVA library 
    // I'd suggest using the http library, it's supported in Xamarin and has better docs
    var client = new HttpClient();
    var data = await client.GetStringAsync(address);
    return data;
}

Upvotes: 1

Related Questions