Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass custom objects to next activity in Xamarin Android

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);
    }
};
like image 700
Tom Spee Avatar asked May 06 '14 08:05

Tom Spee


2 Answers

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");
}
like image 53
harveyslash Avatar answered Sep 18 '22 12:09

harveyslash


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.

like image 37
NutCracker Avatar answered Sep 20 '22 12:09

NutCracker