hugo
hugo

Reputation: 475

xamarin form cannot keep last state

I am trying to keep the state of some variable of my xamarin form when I close the app and start it but is not working

I have 2 variable "isconnected" and "eric"

var app = App.Current;
app.Properties["UserIsConnected"] = true;
app.Properties["userName"] = "eric";
await app.SavePropertiesAsync();

After closing the app when I restart it and trying to get the values of my variable like this :

((bool)App.Current.Properties["UserIsConnected"] )) 
((string)App.Current.Properties["userName"] ))

I have this error:

System.Collections.Generic.KeyNotFoundException: The given key 'UserIsConnected' was not present in the dictionary.

How can I saved my variable and get them when restart the app?

thanks in advance for your help

Upvotes: 0

Views: 78

Answers (2)

Jessie Zhang -MSFT
Jessie Zhang -MSFT

Reputation: 13889

You need to check if the value is exist before we get the value of it. You can do it like this:

private async Task saveDataAsync() {
        if (App.Current.Properties.ContainsKey("UserIsConnected"))
        {
            //Do something awesome.
            bool UserIsConnected = ((bool)App.Current.Properties["UserIsConnected"]);
            string name = ((string)App.Current.Properties["userName"]);
            System.Diagnostics.Debug.WriteLine("UserIsConnected= " + UserIsConnected +" name =" + name);
        }
        else {
            var app = App.Current;
            app.Properties["UserIsConnected"] = true;
            app.Properties["userName"] = "eric";
            await app.SavePropertiesAsync();
        }
    }

Upvotes: 2

Mariano Luis Villa
Mariano Luis Villa

Reputation: 497

You seem to be saving a property with the key "isconnected" and trying to retrieve it with a different key ("UserIsConnected").

EDIT:

OK, thanks for clearing that the error I pointed out was a typo. As for the problem, try this instead:

App.Current.Properties.Add("UserIsConnected", true);
await App.Current.SavePropertiesAsync();

And make sure you check if the key exists before using it:

if (App.Current.Properties.ContainsKey("UserIsConnected"))
{
    //Do something awesome.
}

Upvotes: 0

Related Questions