Created
February 28, 2017 14:41
-
-
Save aspyct/3a51c6b990fe09dc3627fc69e319b16d to your computer and use it in GitHub Desktop.
Android/Xamarin Bundle serialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Runtime.Serialization.Formatters.Binary; | |
using Android.OS; | |
namespace Serialization | |
{ | |
public static class BundleSerializationExtensions | |
{ | |
public static void PutObject(this Bundle self, string key, object obj) | |
{ | |
var formatter = new BinaryFormatter(); | |
var stream = new MemoryStream(); | |
formatter.Serialize(stream, obj); | |
var bytes = stream.ToArray(); | |
self.PutByteArray(key, bytes); | |
} | |
public static T GetObject<T>(this Bundle self, string key) | |
where T : class | |
{ | |
if (self == null) | |
{ | |
return default(T); | |
} | |
var bytes = self.GetByteArray(key); | |
if (bytes == null) { | |
return default(T); | |
} | |
var formatter = new BinaryFormatter(); | |
var stream = new MemoryStream(self.GetByteArray(key)); | |
return formatter.Deserialize(stream) as T; | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Android.App; | |
using Android.Widget; | |
using Android.OS; | |
namespace Serialization | |
{ | |
[Activity(Label = "Serialization", MainLauncher = true, Icon = "@mipmap/icon")] | |
public class MainActivity : Activity | |
{ | |
State state; | |
protected override void OnCreate(Bundle savedInstanceState) | |
{ | |
base.OnCreate(savedInstanceState); | |
state = savedInstanceState.GetObject<State>("state") ?? new State(); | |
// Set our view from the "main" layout resource | |
SetContentView(Resource.Layout.Main); | |
// Get our button from the layout resource, | |
// and attach an event to it | |
Button button = FindViewById<Button>(Resource.Id.myButton); | |
button.Click += delegate { button.Text = $"{state.Count++} clicks!"; }; | |
} | |
protected override void OnSaveInstanceState(Bundle outState) | |
{ | |
base.OnSaveInstanceState(outState); | |
outState.PutObject("state", state); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Serialization | |
{ | |
[Serializable] | |
public class State | |
{ | |
public int Count { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment