DarkW1nter
DarkW1nter

Reputation: 2861

Save string locally on device in Xamarin Forms

I want to save a small piece of data from a Xamarin Forms app locally on a device where it can be retrieved later. I don't want to use SQL Lite, App.Config or save it as a file, it's basically just a string. Is this possible, and if so does anyone have an example?

Upvotes: 3

Views: 4115

Answers (4)

Sreejith Sree
Sreejith Sree

Reputation: 3766

For saving a value to local database:

string userName = "abc.def";
Application.Current.Properties["username"] = userName;
await Application.Current.SavePropertiesAsync();

For retrieving the value in any place of the project:

if (Application.Current.Resources.ContainsKey("username"))
{
    string UserName = Application.Current.Properties["username"].ToString();
}

Use the same key inside [] brackets.

Upvotes: 4

DarkW1nter
DarkW1nter

Reputation: 2861

Using

Application.Current.Properties

only makes the properties, In my case some text, available for the lifetime of the app, if you shut down and re-open they are gone. I ended up using SimpleIoC, it was quite a bit larger than using 1 or 2 lines so will update my answer soon with the code in case anyone wants / needs it

Upvotes: 0

Hichame Yessou
Hichame Yessou

Reputation: 2718

What about the Properties Dictionary?
It's persistent and can be accessed from anywhere!

Application.Current.Properties ["email"] = someClass.email;

Upvotes: 2

OrcusZ
OrcusZ

Reputation: 3660

To store a constant that you need to use in your Xamarin application (Xaml or Code behind) you can use the Application.Resources from App.xaml

https://developer.xamarin.com/guides/xamarin-forms/xaml/resource-dictionaries/

In your App.xaml :

<?xml version="1.0" encoding="UTF-8"?>
<Application xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 xmlns:clr="clr-namespace:System;assembly=mscorlib"
 x:Class="ResourceDictionaryDemo.App">
    <Application.Resources>
        <ResourceDictionary>
    <clr:String x:Key="MyConstString">My string</clr:String>
        </ResourceDictionary>
    </Application.Resources>
</Application>

To access static ressource from XAML :

{StaticResource MyConstString}

From C# :

Application.Current.Resources["resourceName"]

Upvotes: -1

Related Questions