Está en la página 1de 5

Aplicación en .

NET MAUI que lista los usuarios que se


almacenaron con la App de registro de usuarios en un ListView.
En la carpeta del api que realice anteriormente ahí agregue el siguiente
archivo llamado listar.php que obtiene el listado de registro en formato
JSON.
<?php
header("Content-type: application/json; charset=utf-8");
$servername = "localhost";
$username = "id20280252_midbusuario";
$password = "Alumnosxy123$";
$dbname = "id20280252_mibasesita";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM persona";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$registros=array();
$i=0;
while($row = $result->fetch_assoc()) {
// echo "nombre: " . $row["nombre"]. " - usuario: " . $row["usuario"]. " y
contraseña= " . $row["contrasena"]. "<br>";
$registros[$i]=$row;
$i++;
}
echo json_encode($registros);
} else {
echo "0 results";
}
$conn->close();
Interfaz de usuario en XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="ListadoRegistrosDip.MainPage"
Title="Listado de usuarios">

<ScrollView>
<VerticalStackLayout>

<Button Text="Cargar" Margin="5" FontSize="Medium"


Clicked="Button_Clicked" BackgroundColor="Orange" TextColor="White"
CornerRadius="22"/>
<ListView x:Name="lst" HasUnevenRows="True"
ItemTapped="lst_ItemTapped" Margin="5">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<StackLayout Orientation="Vertical">
<Label Text="{Binding nombre}"
FontSize="18"></Label>
<Label Text="{Binding usuario}"
TextColor="Gray"></Label>
<Label Text="{Binding contrasena}"
TextColor="Brown"></Label>
</StackLayout>
<Label Text="{Binding idpersona}"
TextColor="Blue" HeightRequest="30" WidthRequest="50"
HorizontalOptions="EndAndExpand"></Label>

</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</VerticalStackLayout>
</ScrollView>

</ContentPage>

Así se ve la aplicación

Ahora agregaremos el Nuguet Newtonsoft.Json para poder deserealizar las cadenas en formato
JSON.

Ahora te presento el código fuente de la aplicación


namespace ListadoRegistrosDip;
using Newtonsoft.Json;

public partial class MainPage : ContentPage


{
public class Usuarios
{
public int idpersona { get; set; }
public string nombre { get; set; }
public string usuario { get; set; }
public string contrasena { get; set; }
}

List<Usuarios> registros;

HttpClient client;

public MainPage()
{
InitializeComponent();
lst.ItemsSource = new List<Usuarios>() {
new Usuarios() {
nombre = "Becky G", idpersona = 1, usuario = "bbbhyyy",
contrasena="choforo"
},
new Usuarios() {
nombre = "Burro Banrankin", idpersona = 2, usuario = "burro",
contrasena="medusa"
},

};
client = new HttpClient();
client.MaxResponseContentBufferSize = 256000;

public async Task HttpSample()


{

string direccion =
"https://pmoviles2.000webhostapp.com/api/listar.php";
var uri = new Uri(string.Format(direccion, string.Empty));
var response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
var content = await response.Content.ReadAsStringAsync();
registros = JsonConvert.DeserializeObject<List<Usuarios>>(content);
string s = "";
registros.ForEach(delegate (Usuarios x)
{
Console.WriteLine(x.nombre);
s = s + x.nombre + "\n";
});
string mensaje = registros.Count + " Registros \n" + s;
await DisplayAlert("Se cargaron ", mensaje, "OK");
}
}

private async void Button_Clicked(object sender, EventArgs e)


{
lst.BeginRefresh();
await HttpSample();
lst.ItemsSource = null;
lst.ItemsSource = registros;
lst.EndRefresh();

}
private async void lst_ItemTapped(object sender, ItemTappedEventArgs e)
{
var elemento = e.Item as Usuarios;

await DisplayAlert("Se selecciono el registro ", "Usuario:" +


elemento.usuario + "\nNombre:" + elemento.nombre + "\nContraseña:" +
elemento.contrasena, "OK");

}
}

También podría gustarte