Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

c# - 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);
    }
};
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...