Friday, September 12, 2014

Xamarin Android - Application Overview- Using the application class for global variables

Here I just wanted to give a very basic tutorial on how to make a global memory space for an android application so you don't have to constantly read from sharedpreferences or pass things back and forth between activities with bundles.

Create the application class

To start add a blank class to your project and name it whatever you want. I named mine ExampleApp. Then make it inherit the Application class by simply adding : Application. Then add the two methods show below. The code in the OnCreate method will be called before any code in the activity marked as MainLauncher.

Update AndroidManifest.xml

Once you have done that you will need to go to your AndroidManifest.xml and add the android:name to your application tag. make sure that the value of name matches the name of your class that inherited form application. So notice that the value for my android:name is ExampleApp and that is the name of my class that inherits from Application.

Putting it all together

To access (get or set) the public property myString in any other activity use the code below. Since we can get and set variables in the application class we can use this as a mens of passing values back and forth between activities. I am not saying this is the best way, you should be careful about how you use this, just showing another way to handle global variables using Xamarin.Android.

2 comments:

  1. This is an informative article on Xamarin Android - Application Overview- Using the application class for global variables, and helpful for Xamarin Consultants help you in Xamarin Apps Development.

    ReplyDelete
  2. may i ask something? as long ass our app is running android will not delete the global variables? can we be sure about that?

    ReplyDelete