简体   繁体   English

如何在Xamarin.Forms中获取以前的数据

[英]How to get previous data in Xamarin.Forms

I am working on an application which is going to show updated dollar and euro rates for Turkey. 我正在开发一个应用程序,它将显示土耳其的最新美元和欧元汇率。 I want to print green and red arrows depending on if rates went up or down since the last time user opened the app. 我想打印绿色和红色箭头,具体取决于自上次用户打开应用程序以来速率是上升还是下降。 So my question is how can I get previous data and how can I compare them with the current data? 所以我的问题是如何获取以前的数据,以及如何将它们与当前数据进行比较?

CODE-BEHIND; 代码隐藏

namespace Subasi.A.M.D
{
    public partial class MainPage : ContentPage
    {
        float banknoteSellingUSD = 0;
        float banknoteBuyingUSD = 0;

                public MainPage()
        {
            InitializeComponent();

            if (Device.OS == TargetPlatform.iOS)
                Padding = new Thickness(10, 50, 0, 0);
            else if (Device.OS == TargetPlatform.Android)
                Padding = new Thickness(10, 20, 0, 0);
            else if (Device.OS == TargetPlatform.WinPhone)
                Padding = new Thickness(30, 20, 0, 0);
        }






            private void Button_Clicked(object sender, EventArgs e)
            {


                XmlDocument doc1 = new XmlDocument();
                doc1.Load("http://www.tcmb.gov.tr/kurlar/today.xml");
                XmlElement root = doc1.DocumentElement;
                XmlNodeList nodes = root.SelectNodes("Currency");

                foreach (XmlNode node in nodes)
                {

                    var attributeKod = node.Attributes["Kod"].Value;
                    if (attributeKod.Equals("USD"))
                    {

                        var GETbanknoteSellingUSD = node.SelectNodes("BanknoteSelling")[0].InnerText;
                        var GETbanknoteBuyingUSD = node.SelectNodes("BanknoteBuying")[0].InnerText;
                     //if (banknoteSellingUSD > float.Parse(GETbanknoteSellingUSD)) isusdup = false;
                    //else isusdup = true;

                     banknoteSellingUSD = float.Parse(GETbanknoteSellingUSD);
                     banknoteBuyingUSD = float.Parse(GETbanknoteBuyingUSD);
                        labelUSDBuying.Text = banknoteSellingUSD.ToString("0.00");
                        labelUSDSelling.Text = banknoteBuyingUSD.ToString("0.00");




                } 

                    var attributeKod1 = node.Attributes["Kod"].Value;
                    if (attributeKod1.Equals("EUR"))
                    {
                        var GETbanknoteSellingEU = node.SelectNodes("BanknoteSelling")[0].InnerText;
                        var GETbanknoteBuyingEU = node.SelectNodes("BanknoteBuying")[0].InnerText;
                        var banknoteSellingEU = float.Parse(GETbanknoteSellingEU);
                        var banknoteBuyingEU = float.Parse(GETbanknoteBuyingEU);
                        labelEUSelling.Text = banknoteSellingEU.ToString("0.00");
                        labelEUBuying.Text = banknoteBuyingEU.ToString("0.00");





                    }

                }

            }
        }
    }

print green and red arrows depending on if rates went up or down since the last time user opened the app 打印绿色和红色箭头,具体取决于自上次用户打开该应用程序以来汇率是上升还是下降

To achieve this, you will have to store the previous value. 为此,您将必须存储先前的值。 The easiest way may be to use the properties dictionary ( see here ). 最简单的方法可能是使用属性字典( 请参阅此处 )。 You can store simple properties within that. 您可以在其中存储简单的属性。

You could capsule the behavior in a class 您可以将行为封装在一个类中

public class ExchangeCourseSource : IExchangeCourseSource
{
    public ExchangeCourseSource(XmlDocument sourceDocument)
    {
        this.sourceDocument = sourceDocument;
    }

    public ExchangeCourse GetCourse(string currency)
    {
        // parse from XML (see your code)
    }

}

class ExchangeCourse
{
    public string Currency { get; set; }
    public double ExchangeRate { get; set; }
    public double Difference { get; set; }
}

and decorate this with a class that stores and retrieved the courses to and fro the properties dictionary 并用一个类来装饰它,该类存储和检索属性字典中的课程

public class StoredExchangeCourseSourceDecorator : IExchangeCourseSource
{
    public ExchangeCourseSource(IExchangeCourceSource source, Application application)
    {
        this.source = source;
        this.application = application;
    }

    public ExchangeCourse GetCourse(string currency)
    {
        var exchangeCourse = source.GetCourse(currency);
        if(HasStoredCourse())
        {
            var storedCourse = GetStoredCourse(currency);
            exchangeCourse.Difference = exchangeCourse.ExchangeRate - storedCourse;
        }
        StoreCourse(exchangeCourse);
        return exchangeCourse;
    }

    private bool HasStoredCourse(string currency)
    {
        return application.Properties.ContainsKey(currency);
    }

    private double GetStoredCourse(string currency)
    {
        return (double)application.Properties[currency];
    }

    private void StoreCourse(ExchangeCourse exchangeCourse)
    {
        application.Properties[exchangeCourse.Currency] = exchangeCourse.ExchangeRate;
        application.SavePropertiesAsync().Wait();
    }
}

OK, so to answer the question, You have to store data somewhere, the easiest method will be in ISharedPreferences to save and restore data. OK,所以要回答这个问题,您必须将数据存储在某个地方,最简单的方法是在ISharedPreferences中保存和还原数据。

From AndroidDeveloper : 来自AndroidDeveloper

If you don't need to store a lot of data and it doesn't require structure, you should use SharedPreferences. 如果您不需要存储大量数据并且不需要结构,则应使用SharedPreferences。 The SharedPreferences APIs allow you to read and write persistent key-value pairs of primitive data types: booleans, floats, ints, longs, and strings. 使用SharedPreferences API,您可以读写原始数据类型的持久键值对:布尔值,浮点数,整数,长型和字符串。

The key-value pairs are written to XML files that persist across user sessions, even if your app is killed. 键值对将写入到XML文件中,这些文件将在用户会话之间保持持久状态,即使您的应用被终止也是如此。 You can manually specify a name for the file or use per-activity files to save your data. 您可以手动为文件指定名称,也可以使用按活动记录的文件来保存数据。

So it's a good place to store some info and retrieve them. 因此,这里是存储一些信息并检索它们的好地方。

All you have to do is to get an instance from ISharedPreferences and use ISharedPreferencesEditor to insert and retrieve data. 您要做的就是从ISharedPreferences获取实例,并使用ISharedPreferencesEditor插入和检索数据。

You find it in Android.Content Namespace 您可以在Android.Content命名空间中找到它

To save your data you can apply this code : 要保存数据,您可以应用以下代码:

ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(this);
ISharedPreferencesEditor editor = preference.Edit();
editor.PutString("key", "Value");
editor.Apply();

In your case, you can PutFloat 就您而言,您可以PutFloat

So your data which is "Value" is saved with a key named "key" is now saved 因此,现在使用名为"key"的键保存了"Value"数据

then you can retrieve data by : 那么您可以通过以下方式检索数据:

ISharedPreferences preference = PreferenceManager.GetDefaultSharedPreferences(this);
var a = preference .GetString("key", "null");//"null" is the default value if the value not found. and the key, it to retrieve a specific data as we stored the data with the key named "key"

In your case, use GetFloat So you get your value stored in a variable a. 在您的情况下,请使用GetFloat ,以便将值存储在变量a中。

All you have to do is : Store your data in the Sharedpreference when a new data changed or OnSleep() method which will be called when the app closed, then in OnCreate() method in your app, call the data saved in the SharedPreference and compare it with the new data. 您要做的就是:将数据存储在新数据更改时存储在Sharedpreference中,或在应用程序关闭时调用OnSleep()方法,然后在应用程序的OnCreate()方法中,调用保存在SharedPreference中的数据,然后将其与新数据进行比较。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM