Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store data and global variables using the Application object

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?

like image 296
Garry Avatar asked Oct 27 '25 08:10

Garry


2 Answers

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;
like image 197
SKall Avatar answered Oct 29 '25 00:10

SKall


change:

((HelloApplication)GetApplication())

to

((HelloApplication)GetApplicationContext())
like image 34
vipul mittal Avatar answered Oct 28 '25 23:10

vipul mittal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!