I've got a few custom objects like RootObject
and Form
that I want to pass on to the next activity.
This is an example of RootObject
:
public class RootObject
{
public Form Form { get; set; }
}
But how can I pass RootObject
to the next activity with an Intent
and get it in the next Activity
? In Form
there are again multiple properties with Lists
and stuff and I need to access some of the properties in my next Activity
. My intent is called like this:
saveButton.Click += delegate {
if(ValidateScreen()){
SaveData();
Intent intent = new Intent(this, typeof(MainActivity));
Bundle b = new Bundle();
b.PutSerializable("RootObject", RootObject);
StartActivity(intent);
}
};
This is how you can go about it. Your class needs to implement Serializable or Parcelable. In the first Activity(where you want to send from):
final Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("my_class", your_object);
startActivity(intent);
Then in your second Activity, you would do:
final Intent passedIntent = getIntent();
final YourClass my_class = (YourClass) passedIntent.getSerializableExtra("my_class");
There is also another way of doing it, using Bundles::
Create a Bundle from your class like:
public Bundle toBundle() {
Bundle b = new Bundle();
b.putString("SomeKey", "SomeValue");
return b;
}
Then pass this bundle with INTENT. Now you can recreate your class object by passing bundle like
public CustomClass(Context _context, Bundle b) {
context = _context;
classMember = b.getString("SomeKey");
}
I know this is an old question but I think my answer might help someone. What I did is that I used JSON.Net package that you can install with Nuget Manager. By using JSON you can serialize your object in first activity and then deserialize in the second activity. This is how I did it:
Activity 1
using Newtonsoft.Json;
...
void mBtnSignIn_Click(object sender,EventArgs e)
{
User user = new User();
user.Name = "John";
user.Password = "password";
Intent intent = new Intent(this,typeof(Activity2));
intent.PutExtra("User",JsonConvert.SerializeObject(user));
this.StartActivity(intent);
this.Finish();
}
Activity 2
using Newtonsoft.Json;
...
private User user;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Activity2);
user = JsonConvert.DeserializeObject<User>(Intent.GetStringExtra("User"));
}
Hope this would help someone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With