简体   繁体   中英

Passing custom object between Android activities in C#

I am creating an android app in VS2012 using Xamarin.Android. I am displaying a custom list in Main screen. I need to pass a custom object(with ID,String,String,String properties) from this Main activity to another when user clicks on list item.

Can anyone please help me with some example?

edit:

I have already tried solution mention in other question

but the problem is I am getting below exception:

This is how I am extracting in second activity

InsuranceReminderBO i = (InsuranceReminderBO)Intent.GetSerializableExtra("SelectedItemID");

i is null

and in first activity setting it like this:

Intent intent = new Intent(this, typeof(ReminderDetails));

intent.PutExtra("SelectedItemID", selectedInsurance);

StartActivity(typeof(ReminderDetails));

where class InsuranceReminderBO is defined as

public class InsuranceReminderBO : Java.Lang.Object, Java.IO.ISerializable

I have also tried using IParcelable but in that I got error Creator is not defined in ICreator or Creator

Following the implementation of Iparcelable on CustomObject

'public class InsuranceReminderBO : Java.Lang.Object, IParcelable
    {
        public InsuranceReminderBO()
        {
        }

        #region Objects and Properties
        private int id;
        private String strCompanyName;
        private String strPremiumAmount;
        private String stDueDate;

        public int ID
        {
            get { return this.id; }
            set { this.id = value; }
        }

        public String Company_Name
        {
            get { return this.strCompanyName; }
            set { this.strCompanyName = value; }
        }

        public String Premium_Amount
        {
            get { return this.strPremiumAmount; }
            set { this.strPremiumAmount = value; }
        }

        public String Due_Date
        {
            get { return this.stDueDate; }
            set { this.stDueDate = value; }
        }
        #endregion

        #region IParcelable implementation

        // The creator creates an instance of the specified object
        private static readonly GenericParcelableCreator<InsuranceReminderBO> _creator 
            = new GenericParcelableCreator<InsuranceReminderBO>((parcel) => new InsuranceReminderBO(parcel));

        [ExportField("CREATOR")]
        public static GenericParcelableCreator<InsuranceReminderBO> GetCreator()
        {
            return _creator;
        }

        // Create a new SelectListItem populated with the values in parcel
        private InsuranceReminderBO(Parcel parcel)
        {
            ID = parcel.ReadInt();
            Company_Name = parcel.ReadString();
            Premium_Amount = parcel.ReadString();
            Due_Date = parcel.ReadString();
        }

        public int DescribeContents()
        {
            return 0;
        }

        // Save this instance's values to the parcel
        public void WriteToParcel(Parcel dest, ParcelableWriteFlags flags)
        {
            dest.WriteInt(ID);
            dest.WriteString(Company_Name);
            dest.WriteString(Premium_Amount);
            dest.WriteString(Due_Date);
        }

        // Closest to the 'Java' way of implementing the creator
        /*public sealed class SelectListItemCreator : Java.Lang.Object, IParcelableCreator
        {
            public Java.Lang.Object CreateFromParcel(Parcel source)
            {
                return new SelectListItem(source);
            }

            public Java.Lang.Object[] NewArray(int size)
            {
                return new SelectListItem[size];
            }
        }*/

        #endregion
    }

#region GenericParcelableCreator
    /// <summary>
    /// Generic Parcelable creator that can be used to create objects from parcels
    /// </summary>
    public sealed class GenericParcelableCreator<T> : Java.Lang.Object, IParcelableCreator
        where T : Java.Lang.Object, new()
    {
        private readonly Func<Parcel, T> _createFunc;

        /// <summary>
        /// Initializes a new instance of the <see cref="ParcelableDemo.GenericParcelableCreator`1"/> class.
        /// </summary>
        /// <param name='createFromParcelFunc'>
        /// Func that creates an instance of T, populated with the values from the parcel parameter
        /// </param>
        public GenericParcelableCreator(Func<Parcel, T> createFromParcelFunc)
        {
            _createFunc = createFromParcelFunc;
        }

        #region IParcelableCreator Implementation

        public Java.Lang.Object CreateFromParcel(Parcel source)
        {
            return _createFunc(source);
        }

        public Java.Lang.Object[] NewArray(int size)
        {
            return new T[size];
        }
        #endregion
    }
#endregion'

I am putting object in intent as

InsuranceReminderBO selectedInsurance = listOfInsurance[e.Position];
Intent intent = new Intent(this, typeof(ReminderDetails));
            intent.PutExtra("SelectedItem", selectedInsurance);

And reading in second activity as

InsuranceReminderBO i = (InsuranceReminderBO)Intent.GetParcelableExtra("SelectedItem");

but getting i as null.

To coat tail on the servicestack.text solution, you can just download the android DLL's and reference them into your solution. You can use this and add it to your solution, build it separately, as alternatives. https://github.com/ServiceStack/ServiceStack.Text/tree/master/src/ServiceStack.Text.Android

Also I use a couple of methods to convert items back and forth that may be helpful, try

static public string ToJSON(this object item)
{
  var myval = JsonSerializer.SerializeToString(item);
  return myval;
}
static public T FromJSON<T>(string code)
{
   var item = JsonSerializer.DeserializeFromString<T>(code);
   return item;
}

There's an article on using IParcelable in Xamarin here .

Personally, I've always just serialised to JSON, passed a string extra and deserialised it on the other end.

If you're using ServiceStack.Text , which I like, you can do something like this:

intent.PutExtra("SelectedItemId", JsonSerializer.SerializeToString(selectedInsurance));

And on the other end:

var insurance = JsonSerializer.DeserializeFromString<InsuranceReminderBO>(Intent.GetStringExtra("SelectedItemId"))

No need to implement Java.Lang.Object, Java.IO.ISerializable

After doing a lot of search on Google finally i found a solution here .

Basically I used StartActivity(intent);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM