Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass data from one activity to another in Xamarin.Android

I wanted to pass a Class Object from one activity to another in Xamarin.Android app. I can pass the simple strings using Intent.PutExtra method.

Does anybody know about it. anyhelp is appreciated :)

like image 635
loop Avatar asked Sep 25 '14 19:09

loop


2 Answers

Just adding in case someone else comes across this. The nice thing about Xamarin/.NET is how easy it is to use JSON. You can Serialize your data to a string and pass that through the Extras.

JSON.NET is a nice library (that you can find on the Xamarin component store) for this and there is also some built in JSON classes in .NET. An example using JSON.NET would be like this.

Intent i = new Intent(Application.Context, typeof(SecondActivity));
i.PutExtra("key", JsonConvert.SerializeObject(myObject));
StartActivity(i);

And in the other Activity you can deserialize it.

var obj = JsonConvert.DeserializeObject<OBJ_TYPE>(Intent.GetStringExtra("key"));

This is better than using a static reference in my opinion.

like image 192
kevskree Avatar answered Sep 21 '22 21:09

kevskree


The concept is the same as with a standard (non-Xamarin) application.

You can use Intent#putExtra(String, Parcelable) to pass any object that implements the Parcelable interface as an extra.

The Parcelable interface is a little bit complex, so be sure to read the documentation to ensure that your class conforms to the requirements. You may also want to check out this SO question for more information on creating a Parcelable class.

You cannot pass an object reference via an Intent. This is because Activities are designed to work completely independently of each other. Users can throw your Activity in the background while performing other tasks, so it is entirely possible (and very likely) that your Activity's variables will be garbage collected. When the user later comes back to your Activity, it should be able to recreate its state.

If you really need to pass a reference to an object directly, you can do so by making that object a static variable. While this is a quick and dirty way to solve the problem of getting data from one Activity to another, it does not solve the problem of the variable potentially being garbage collected at some point, and is generally a poor design choice.

like image 34
Bryan Herbst Avatar answered Sep 22 '22 21:09

Bryan Herbst