Reputation: 1746
I need to pass a multidimensional array to another activity. This is how I want to be able to do it:
int[,,] aMultidimensionalArray = new int[a,b,c];
Intent intent = new Intent(this.Activity, typeof(outputActivity));
intent.PutExtra("array", aMultidimensionalArray);
StartActivity(intent);
However the compiler is saying that the aMultidimesionalArray
is not serialisable. This led me to having to use int[][][]
to declare the array which then leads to a whole host of other issues down the rest of my code.
Upvotes: 1
Views: 123
Reputation: 2518
Use this Json.NET component to serialize the array
Here is a simple example to serialize and deserialize an array
using Newtonsoft.Json;
...
public class Person
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
}
void PersonToJsonToPersonExample ()
{
var person = new Person { Name = "Bob", Birthday = new DateTime (1987, 2, 2) };
var json = JsonConvert.SerializeObject (person);
Console.WriteLine ("JSON representation of person: {0}", json);
var person2 = JsonConvert.DeserializeObject<Person> (json);
Console.WriteLine ("{0} - {1}", person2.Name, person2.Birthday);
}
You can also use The Application class to store objects globally and retrieve them:
using Android.Runtime;
namespace SomeName
{
[Application]
public class App : Application
{
public string Name { get; set;}
public App (IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
public override void OnCreate ()
{
base.OnCreate ();
Name = "";
}
}
}
And you can access the data with:
App application = (App)Application.Context;
application.Name = "something";
I choose to do this on the Application
calss because this class is called on the App startup so you don't have to initiate it manually.
Keep in mind that variables which are scoped to the Application
have their lifetime scoped to the application by extension.
This class will be Garbage Collected if the Android feels it is necessary so you have to modify the code to include this case also.
You can use SharedPreferences
or a Database
to save your variables in case they get deleted and retrieve them from the App class for faster results.
Don't be overly wasteful in how you use this approach though, as attaching too much information on this class it can lead to a degradation in performance. Only add information that you know will be needed by different parts of the application, and where the cost of retrieving that information exceeds the cost of storing it as an application variable.
Investigate which information you need to hold as application wide state, and what information can simply be retrieved straight from your database. There are cost implications for both and you need to ensure you get the balance right.
And don't forget to release resources as needed on OnStop
and OnDestroy
.
Upvotes: 4