Transfer data from one activity to another in Xamarin.Android

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

Does anyone know about this. anyhelp is rated :)

+6
source share
2 answers

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

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

The Parcelable interface Parcelable bit complicated, so be sure to read the documentation to make sure your class meets the requirements. You can also view this SO question for more information on creating a Parcelable class.

You cannot pass a reference to an object through Intent . This is due to the fact that actions are designed to work completely independently of each other. Users can throw your activity in the background while performing other tasks, so it is quite possible (and very likely) that your Activity variables will be garbage collected. When the user later returns to your activity, he should be able to recreate his state.

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

+3
source

Just add if anyone else comes across this. The good thing about Xamarin / .NET is how easy it is to use JSON. You can Serialize your data to a string and pass this through Extras.

JSON.NET is a good library (which you can find in the Xamarin component repository) for this, and there are 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 another Activity you can deserialize it.

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

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

+12
source

Source: https://habr.com/ru/post/975854/


All Articles