How to save any string in MAUI app using android after app is closed?

My issue is very simple and I am new using MAUI at work and I am struggling on how to store anything like a string in a MAUI android app.

I have read Microsoft docs on how to store a string in the device: https://learn.microsoft.com/en-us/dotnet/maui/platform-integration/storage/secure-storage?view=net-maui-7.0&tabs=android

but my code is not working and I do not know why it is not working. I have this so far:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         x:Class="SecureStorageTest1.MainPage">

<ScrollView>
    <VerticalStackLayout
        Spacing="25"
        Padding="30,0"
        VerticalOptions="Center">

        <Label
            x:Name="lblguid"
            SemanticProperties.HeadingLevel="Level2"
            SemanticProperties.Description="Welcome to dot net Multi platform App U I"
            FontSize="18"
            HorizontalOptions="Center" />

        <Button
            x:Name="CounterBtn"
            Text="Generate Token and Save"
            SemanticProperties.Hint="Counts the number of times you click"
            Clicked="OnCounterClicked"
            HorizontalOptions="Center" />

    </VerticalStackLayout>
</ScrollView>
    static string Token = "there is no guid set";

public MainPage()
{
    InitializeComponent();

    lblguid.Text = Token;
}

private async void OnCounterClicked(object sender, EventArgs e)
{

    string oauthToken = await SecureStorage.Default.GetAsync(Token);

    if (oauthToken == null)
    {
        // No value is associated with the key "oauth_token"

        var tk = await GenerateAndSave();
        lblguid.Text = tk.ToString();
    }
    else
    {
        lblguid.Text = oauthToken;
    }
}

private async Task<string> GenerateAndSave()
{
    var guid = Guid.NewGuid();

    await SecureStorage.Default.SetAsync(guid.ToString(), guid.ToString());

    Token = guid.ToString();

    return Token;
}

I am using Android emulator in my PC. I am trying to keep the generated Guid FOREVER on the phone until it is formatted or it is a new phone.

How can I solve this?

enter image description here

>Solution :

you need to specify the same Key value when you save and load the token

save

await SecureStorage.Default.SetAsync("MyKey", guid.ToString());

load

string oauthToken = await SecureStorage.Default.GetAsync("MyKey");

Leave a Reply