jsonxamarinrequest

How to select data and put it on label text coming from HTTP request in Xamarin


I am very beginner in Xamarin. I have a PHP page which fetches JSON data for one user:

<?php
include_once 'DbConnect.php';
$username = $_GET['username'];
$username = strip_tags($username);
$username = trim($username);
$username = stripslashes($username);
$username = mysqli_real_escape_string($connection, $username);
 
$user = "SELECT * FROM users Where username = '$username'";
$result = mysqli_query($connection, $user);
$user_status = array();
foreach ($result as $row) {
    array_push($user_status, array(
        's_id' => $row['s_id'],
        'm_id' => $row['m_id'],
        'd_id' => $row['d_id'],
    ));
}
echo utf8_encode(json_encode($user_status));
?>

On a page on Xamarin, I request this page to get data above:

private async void GetStatus()
{
    HttpClient MyStatus = new HttpClient();
    var responsestatus = await MyStatus.GetStringAsync("xxx/api/userstatus.php?username=" + myparam.Text);
    var myStatus = JsonConvert.DeserializeObject<List<Models.UserStatus>>(responsestatus);

    var Result = from MyItem in myStatus
    select MyItem;
}

So I have this Class Model:

class UserStatus
{
    public string s_id { get; set; }
    public string m_id { get; set; }
    public string d_id { get; set; }
}

Now I receive one row of ( s_id ,m_id and d_id ). I want to put each one of them on label text to show them. How can I do that?


Solution

  • create a XAML page with three Labels and give them names

    <ContentPage ... >
      <ContentPage.Content>
        <StackLayout>
         <Label x:Name="Label1" />
         <Label x:Name="Label2" />
         <Label x:Name="Label2" />
        </StackLayout>
      </ContentPage.Content>
    </ContentPage>
    

    then in your xaml.cs page, after you receive your data

    HttpClient MyStatus = new HttpClient();
    var responsestatus = await MyStatus.GetStringAsync("xxx/api/userstatus.php?username="+ myparam.Text);
    var myStatus = JsonConvert.DeserializeObject<List<Models.UserStatus>>(responsestatus);
    
    Label1.Text = myStatus[0].s_id;
    Label1.Text = myStatus[0].m_id;
    Label1.Text = myStatus[0].d_id;