Forum Xamarin.Android
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

Display a random amount of results from Json api.

Hello, 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://catfacts-api.appspot.com/api/facts?number=5 will display 5 facts and http://catfacts-api.appspot.com/api/facts 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://catfacts-api.appspot.com/api/facts";
            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];
    }

}

}

`


Best Answer

Answers

Sign In or Register to comment.