I am writing Android app in Xamarin C#.
I parse info from JSON and then show it in fields.
I use this code:
string url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
JsonValue json = await FetchAsync(url2);
private async Task<JsonValue> FetchAsync(string url)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//dynamic data = JObject.Parse(jsonDoc[15].ToString);
Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
// Return the JSON document:
return jsonDoc;
}
}
}
But I have one problem. When I open Activity it freezes for 2-3 seconds and then all info shows in fields.
Can I make that data download smoothly. First field, then second etc.
And if I can, how?
I would recommend implementing the proper usage of async/await in C#, and switching to HttpClient, which also implements the proper usage of async/await. Below is a code sample that will retrieve your Json outside of the UI Thread:
var url2 = "http://papajohn.pp.ua/?mkapi=getProductsByCat&cat_id=74";
var jsonValue = await FetchAsync(url2);
private async Task<JsonValue> FetchAsync(string url)
{
System.IO.Stream jsonStream;
JsonValue jsonDoc;
using(var httpClient = new HttpClient())
{
jsonStream = await httpClient.GetStreamAsync(url);
jsonDoc = JsonObject.Load(jsonStream);
}
return jsonDoc;
}
If you're writing your code in an Android project, you'll need to add the System.Net.Http DLL as a reference. If you're writing your code in aPCL, then you'll need to install the Microsoft Http Client Libraries Nuget Package. For even improve performance, I recommend using ModernHttpClient, which can also be installed from Nuget.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With