dimanche 23 avril 2017

C# webrequest returning Json value, outputing amount of the results using Random

I am working on a little exercise for fun using the Cat Facts api. The problem I am running into, is not by displaying a random 'cat fact' one at a time. But by displaying a random amount of facts up to five total. Im attempting to everything in one activity/class. http://ift.tt/1DHIbuC will display 5 facts and http://ift.tt/1Kai8Pf will return one. This is how my code looks thus far,

public class MainActivity : Activity
{
private ImageButton _mrWhiskersButton;
private TextView _catFactsTextView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        _mrWhiskersButton = FindViewById<ImageButton>(Resource.Id.imageCatButton);
        _catFactsTextView = FindViewById<TextView>(Resource.Id.catFactsText);

        _mrWhiskersButton.Click += async delegate
        {


            string url = "http://ift.tt/1Kai8Pf";
            JsonValue json = await FetchInfoAsync(url);
            updateCats(json);
        };

    }
    public async Task<JsonValue> FetchInfoAsync(string url)
    {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url));
        request.ContentType = "application/json";
        request.Method = "GET";

        using (WebResponse response = await request.GetResponseAsync())
        {
            using (Stream stream = response.GetResponseStream())
            {
                JsonValue jsonDoc = await Task.Run(() => JsonValue.Load(stream));
                Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
                return jsonDoc;
            }
        }
    }

    private void updateCats(JsonValue json)
    {

        _catFactsTextView.Text = json["facts"][0];
    }

}
}




Aucun commentaire:

Enregistrer un commentaire