Press ESC to close

Xamarin Forms Currency Application

Hello friends. In this article, we will make a simple application with Xamarin Forms. In this application, we will instantly take the exchange rates from a website and show them on the screen. At the same time, there will be a refresh feature in the list, so that every time we renew it, it will receive the data again.

It is a simple mobile application. We will use the data of BTCTurk to get currency data. You can access the web service from here.

Then we will make a simple design. We will create a screen and assign ListView to this screen. With this List View, we will show the data from the service on the screen. I used ListView here because I created it in Xamarin Forms project, but you can customize it according to the platform you wrote. The main thing here is to pull data from a service. Simply, my screen design is as follows.

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamCurrency.Views.CurrencyPage">
    <ContentPage.Resources>
        <Style TargetType="Label" x:Key="labelStyle">
            <Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
            <Setter Property="VerticalOptions" Value="CenterAndExpand"/>
            <Setter Property="HorizontalTextAlignment" Value="Center"/>
            <Setter Property="VerticalTextAlignment" Value="Center"/>
            <Setter Property="TextColor" Value="Black"/>
            <Setter Property="FontSize" Value="Medium"/>
        </Style>
        <Style TargetType="Label" x:Key="labelStyleTitle">
            <Setter Property="HorizontalOptions" Value="CenterAndExpand"/>
            <Setter Property="VerticalOptions" Value="CenterAndExpand"/>
            <Setter Property="HorizontalTextAlignment" Value="Center"/>
            <Setter Property="VerticalTextAlignment" Value="Center"/>
            <Setter Property="TextColor" Value="Red"/>
            <Setter Property="FontSize" Value="Large"/>
        </Style>
    </ContentPage.Resources>
    <ContentPage.Content>
        <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <ListView HorizontalOptions="FillAndExpand"
                      VerticalOptions="FillAndExpand"
                      x:Name="listViewCurrency"
                      IsPullToRefreshEnabled="True"
                      Refreshing="ListViewCurrency_Refreshing"
                      RowHeight="80">
                <ListView.Header>
                    <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand" HeightRequest="80">
                        <Grid.ColumnDefinitions>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                            <ColumnDefinition Width="*"/>
                        </Grid.ColumnDefinitions>
                        <Label Grid.Column="0"
                               Style="{StaticResource labelStyleTitle}"
                               Text="Pair"/>
                        <Label Grid.Column="1"
                               Style="{StaticResource labelStyleTitle}"
                               Text="High"/>
                        <Label Grid.Column="2"
                               Style="{StaticResource labelStyleTitle}"
                               Text="Low"/>
                        <Label Grid.Column="3"
                               Style="{StaticResource labelStyleTitle}"
                               Text="Current"/>
                    </Grid>
                </ListView.Header>
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <ViewCell.View>
                                <Grid HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="*"/>
                                        <ColumnDefinition Width="*"/>
                                    </Grid.ColumnDefinitions>
                                    <Label Grid.Column="0"
                                           Style="{StaticResource labelStyle}"
                                           Text="{Binding pair}"/>
                                    <Label Grid.Column="1"
                                           Style="{StaticResource labelStyle}"
                                           Text="{Binding high}"/>
                                    <Label Grid.Column="2"
                                           Style="{StaticResource labelStyle}"
                                           Text="{Binding low}"/>
                                    <Label Grid.Column="3"
                                           Style="{StaticResource labelStyle}"
                                           Text="{Binding last}"/>
                                </Grid>
                            </ViewCell.View>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
            <ActivityIndicator x:Name="indicator"
                               HorizontalOptions="CenterAndExpand"
                               VerticalOptions="CenterAndExpand"
                               HeightRequest="50"
                               WidthRequest="50"
                               Color="Red"
                               IsRunning="False"/>
        </Grid>
    </ContentPage.Content>
</ContentPage>

We actually used a ListView and an Acitivity Indicator here. We will use the data we receive in this ListView. On the other hand, Activity Indicator is used to draw data from the service to indicate to the user that we have done something in the background. There are 4 fields in ListView. These; It has the name, the highest value, the lowest value and the current value.

As the last operation, we renew the data every time we renew ListView. The application briefly works as follows:

The cs part of the project is as follows;

using System;
using System.Collections.Generic;

using Xamarin.Forms;
using XamCurrency.Models;

namespace XamCurrency.Views
{
    public partial class CurrencyPage : ContentPage
    {
        Service service;
        public CurrencyPage()
        {
            InitializeComponent();
            service = new Service();
            FillCurrencies();
        }

        private void ListViewCurrency_Refreshing(object sender, EventArgs e)
        {
            listViewCurrency.IsRefreshing = true;
            FillCurrencies();
            listViewCurrency.IsRefreshing = false;
        }

        private async void FillCurrencies()
        {
            indicator.IsRunning = true;
            var takenData = await service.GetAsync<List<CurrencyModel>>("https://www.btcturk.com/api/ticker?fbclid=IwAR3-RzMvjpF18zGH3gW5uLxzbVE4kexILcK-e3ufQNopkjhiWC1zLcGL5Ow");
            if (takenData != null)
            {
                listViewCurrency.ItemsSource = takenData;
            }
            indicator.IsRunning = false;
        }
    }
}

The service part is a simple structure like this:

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace XamCurrency
{
    public class Service
    {
        HttpClient httpClient;

        public async Task<TResult> GetAsync<TResult>(string uri)
        {
            if (Xamarin.Essentials.Connectivity.NetworkAccess == Xamarin.Essentials.NetworkAccess.Internet)
            {
                try
                {
                    httpClient = new HttpClient();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    HttpResponseMessage response = await httpClient.GetAsync(uri);
                    string serialized = await response.Content.ReadAsStringAsync();
                    TResult result = await Task.Run(() => JsonConvert.DeserializeObject<TResult>(serialized, new JsonSerializerSettings
                    {
                        MissingMemberHandling = MissingMemberHandling.Ignore
                    }));

                    return result;
                }
                catch (Exception e)
                {
                    return default(TResult);
                }
            }
            else
            {
                return default(TResult);
            }
        }
    }
}

If there are friends who have questions, they can reach me by e-mail or comment. Good work everyone.

You can access the project from Github link.

Comments (4)

Leave a Reply

Your email address will not be published. Required fields are marked *