Search code examples
c#androidxamarinrandomhttpwebrequest

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 i am trying to display a random amount of facts up to five total. For example, user clicks the button gets 3 facts, user clicks the button again and gets 1 fact, user clicks the button a third time and either gets 1, 2, 3, 4 or 5 facts. Im attempting to do 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];
    }

}
}

Solution

  • public class MainActivity : Activity
    {
      private ImageButton _mrWhiskersButton;
      private TextView _catFactsTextView;
      private System.Random rand;
    
      protected override void OnCreate(Bundle bundle)
      {
        base.OnCreate(bundle)
    
        rand = new System.Random();
    
        // omitted code...
    
        _mrWhiskersButton.Click += async delegate
        {
            // get next random int between 1 and 5
            int ndx = rand.Next(1,5);
            string url = $"Http://catfacts-api.appspot.com/api/facts?number={ndx}";
            JsonValue json = await FetchInfoAsync(url);
            updateCats(json);
        };
    
    }
      private void updateCats(JsonValue json)
      {
          foreach (var fact in json["facts"]) {
            _catFactsTextView.Text += fact + "\n";          
          }
    
      }