Forum Xamarin.Android

What is the most straightforward way to make data persist across events?

EliasSimonEliasSimon USMember ✭✭
edited June 2019 in Xamarin.Android

Let's say I want to count the number of times a user pushes a button. But I want the click handler to be defined externally to MainActivity.

public class MainActivity : Activity
{
    int Count;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        Button button = FindViewById<Button>(Resource.Id.MyButton);
        button.Click += MyHandlers.ButtonClick;
    }
}

public static class MyHandlers
{
    public ButtonClick(object sender, EventArgs e)
    {
       Count++;
    }
}

I know I could define a UI element and keep setting/getting it, but that seems inefficient. I've looked into doing something like using Android.App.Application.Context, or the solution proposed in this thread, but trying to do something like "MainApplication.CurrentContext.Count++" from ButtonClick doesn't seem to work.

I'm not using Xamarin.Forms and I'd rather not install an entire NuGet package for something that seems like it should be simple.

Best Answer

Answers

  • EliasSimonEliasSimon USMember ✭✭

    Thanks! Using a static class seems to work. To clarify, what do you mean "when app closed"? Would the state of MyHandlers.Count class's data persist until the Activity is destroyed?

  • LandLuLandLu Member, Xamarin Team Xamurai

    @EliasSimon No, even though the Acitivy is destroyed the data won't be lost. I mean when the user force quit and reopen the app, everything will be refreshed.

Sign In or Register to comment.