In a solution with two projects: one Xamarin.Forms and the other Android (Xamarin), I need to use in the first the value of a variable generated in the second. I've tried declaring the variable as Global, but it doesn't work outside of your project. I would like to know what is the best alternative. Note that this is not a variable between classes in a project but between projects in a solution.
After looking at the documentation I have opted for a solution that works. It involves using a folder on the mobile device to write the value of the variable to a text file. I have tested with both projects and it can be accessed without problems to write and to read. For those who may be interested in this way of doing it, I will explain it in more detail.
In an Android (Xamarin) activity of the first project I write the data in the text file memo.txt as follows:
To write to the text file:
With the File class , if the file does not exist, we create it in the previously formed FileName route. This path has two parts: the first takes the path of LocalApplicationData on the device, and the second is the name of the text file " memo.txt ". The value of the string that is written is " F " (variable previously generated by the application flow).
Once the second project, Xamarin.Forms, is loaded, I retrieve the value written in the text file like this:
To read from the text file:
New edition.-
Including the writing and reading of the text file within asynchronous tasks I have verified that there is no crash on the Android device. I haven't tried it on Mac yet. It would be like this.
To write:
And to read:
I have found what seems to be the ultimate solution for my query. This is the Properties property of the Xamarin.Forms Application object . It is possible to write and access the values that we store in it from any project in the solution. In the following way:
And to get the stored values:
I have tested it and it works fine. It is very fast and clean as it does not cause any lockup on the device even with recursive accesses at intervals of milliseconds.
You need to write the value using an Object . I have done it this way.
I have a class in which there is a FREQUENCY property .
I declare an instance of that class and give it the desired value.
Now I store the value in the property of the Application object .
And to read the data at any other point in the current project or from another in the solution:
As you can see, it is necessary to convert from Object to the desired type since the property is saved as Object . In this specific case, the type of the FREQUENCY variable is float and it is recovered converted to string .
It is important to point out that it is very convenient to check before reading the data that the saved key actually exists. For this it is used:
Cheers