Store data and global variables using the Application object

10,520

Solution 1

Looking at the code you could just make the variable a public static.

public class HelloApplication : Application 
{
    public static int GlobalVariable = 1;
}

Usage:

HelloApplication.GlobalVariable = 10;

Solution 2

change:

((HelloApplication)GetApplication())

to

((HelloApplication)GetApplicationContext())
Share:
10,520
Garry
Author by

Garry

Updated on June 04, 2022

Comments

  • Garry
    Garry about 2 years

    In Xamarin, I am wanting to store data and global variables using the Application object.

    I looked at this resource for this code: http://www.helloandroid.com/tutorials/maintaining-global-application-state

    Here is my code:

        public class HelloApplication : Application 
        {
            private int GlobalVariable = 1;
    
            public int GetGlobalVariable()
            {
                return GlobalVariable;
            }
    
            public void SetGlobalVariable(int GlobalVariable)
            {
                this.GlobalVariable = GlobalVariable;
            }
        }
    

    I am trying to reference the class using this code:

        ((HelloApplication)GetApplication()).setGlobalVariable(10);
        int variable=((HelloApplication)GetApplication()).getGlobalVariable();
    

    When I build the application I am getting this error for both the above lines of code:

    The name 'GetApplication' does not exist in the current context

    Can I please have some help to get this code working?

    EDIT

    Here is my code:

    HelloApplication state = ((HelloApplication) this.ApplicationContext);
    state.SetGlobalVariable(10);
    int globalVariable = state.GetGlobalVariable ();
    
    Toast.MakeText (this, "Global variable " + globalVariable, ToastLength.Short).Show ();
    

    This is the error I am getting:

    UNHANDLED EXCEPTION: System.InvalidCastException: Cannot cast from source type to destination type.

    Can I please have some help to get this working?