show api data (Xamarin Forms)

Viewed 88

i want to see API data on screen 2 without button click. Although i am getting that data on screen 1 when i run it now i want same data to be seen on the next screen without clicking button on next screen as i done in screen 1 This is the code for Screen 2 xaml

<StackLayout>

    <Label Text="this is second page"

            x:Name="displaylabel"

        VerticalOptions="CenterAndExpand" 
        HorizontalOptions="CenterAndExpand" />

This is the code for screen 2 xaml.cs

public partial class Data : ContentPage
    {
        private static readonly HttpClient client = new HttpClient();
        // private String data;
        public String show;
        //String responseString;
        public Data(String data)
        {
            InitializeComponent();
            displaylabel.Text = show;

        }
        public async Task GetinfoAsync()
        {

            var responseString = await client.GetStringAsync("https://reqres.in/api/users/2");
            show = responseString;
           // DisplayAlert("text", responseString, "ok");
            displaylabel.Text = show;


        }
        public void view()
        {
            DisplayAlert("show", GetinfoAsync, "OK!");
        }

        private void DisplayAlert(string v1, Func<Task> getinfoAsync, string v2)
        {
            throw new NotImplementedException();
        }
1 Answers

You can use a ViewModel and bind a property to your label in xaml and call a function from your page constructor to update it.

Or you can try this:

    public Data(String data)
    {
        InitializeComponent();

        Task.Run(async() => await GetinfoAsync());
    }

    public async Task GetinfoAsync()
    {

        var responseString = await 
        client.GetStringAsync("https://reqres.in/api/users/2");
        show = responseString;
       // DisplayAlert("text", responseString, "ok");

       Device.BeginInvokeOnMainThread(()=>{
          displaylabel.Text = show;
       });
    }
Related