Press ESC to close

Xamarin Forms Döviz Uygulaması

Merhaba arkadaşlar. Bu yazımda Xamarin Forms ile basit bir uygulama yapacağız. Bu uygulamada, bir web sitesinden anlık olarak döviz kurlarını alacağız ve ekranda bunları göstereceğiz. Aynı zamanda listede yenileme özelliği olacak bu sayede her yenilediğimizde verileri yeniden alacak.

Basit bir mobil uygulama aslında. Döviz verilerini almak için BTCTurk’un verilerini kullanacağız. Web servise buradan ulaşabilirsiniz.

Sonrasında basit bir tasarım yapacağız. Bir ekran oluşturup bu ekrana ListView atayacağız. Bu List View ile servisten gelen verileri ekranda göstereceğiz. Xamarin Forms projesinde oluşturduğum için burada ListView kullandım ama siz yazdığınız platforma göre bunu özelleştirebilirsiniz. Burada asıl önemli olan bir servisteki verileri çekmek. Basit olarak ekran tasarımım aşağıda ki gibidir.

<?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>

Burada aslında basit bir şekilde bir ListView ve bir Acitivity Indicator kullandık. Aldığımız verileri bu ListView içerisinde kullanacağız. Activity Indicator ise servisten veri çekerken kullanıcıya arka planda bir işlem yaptığımızı belirtmek için koyuyoruz. ListView’in içerisinde ise 4 adet alan var. Bunlar; adı, en yüksek değeri, en düşük değeri ve güncel değeri bulunmakta.

En son işlem olarak ise ListView’iher yenilediğimizde verileri de yeniliyoruz. Uygulama kısaca şu şekilde çalışıyor:

 

Projenin cs kısmı şu şekilde;

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;
        }
    }
}

Servis kısmı ise bu şekilde basit bir yapı:

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);
            }
        }
    }
}

Sorusu olan arkadaşlar var ise mail veya yorum atarak bana ulaşabilirler. Herkese iyi çalışmalar.

Projeye Github linkinden ulaşabilirsiniz.

Comments (4)

  • Mehmetsays:

    Salı Aralık 17th, 2019 at 22:38

    Merhaba paylaşımınız için teşekkür ederim. xamarin.forms ile android ve ios’ta arka pilanda watsapp gibi çalışacak bşr servis alt yapısı ile mi yazdınız öyle ise kodları inceleyeceğim ve çok işime yarayacak. Bir çok kod inceledim bir haftadır uğraşıyorum olmadı. Yardımınızı rica ediyorum.

    • omersezersays:

      Cumartesi Aralık 21st, 2019 at 10:53

      Selam Mehmet,

      Şu anda bu kod sadece uygulama açıkken çalışıyor ve sayfa ilk yüklendiginde ayrıca listeyi yenilerken calisiyor. Yapmak istediğin şeyi tam olarak soylersen daha çok yardımcı olabilirim.

Mehmet için bir yanıt yazın Yanıtı iptal et

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir