开发者

Trouble using parcels to send Object of unknown datatype

开发者 https://www.devze.com 2023-02-03 04:19 出处:网络
I asked a question the other day regarding sending an object to an activity using an intent as a parcel but I am unsure how to do it in my situation. I have a variable of type object Object x; which i

I asked a question the other day regarding sending an object to an activity using an intent as a parcel but I am unsure how to do it in my situation. I have a variable of type object Object x; which is set with something like this: x = edit.getText().toString(); and in this instance x becomes a String object but I also have it able to set x as both an Integer and an SQLDate type. Looking at examples of how to send an object as a parcel it seems to me you have to know what the datatype is before hand even for custom datatypes. Any help with this will be greatly appreciated as i'm completely stuck 开发者_如何学Pythonon this.

Flow is:

Object x; - is created.

x = String object||Integer object||sqldate object - x is assigned a value

i.putExtra("object", x); - x is sent through to the next activity after being parcelled.


The requirement on the data you pass inn is that it is serializable in some way, and yes, both String and Integer are. Also, if you're using java.sql.Date, this type inherits util.Date which in turn inherits Serializable. The slight "problem" is that Intent.putExtra does not have an overload that takes Object as parameter type. Thus, you would have to "know" which data type you want to put:

if (goingToUseStringObject...)
{
    // use the CharSequence overload
    i.putExtra("object", stringObject);
}
else if (goingToUseIntegerObject...)
{
    // use the int overload
    i.putExtra("object", integerObject);
}
else if (goingToUseDateObject...)
{
    // use the Serializable overload
    i.putExtra("object", dateObject);
}


Rather than having an Object reference that can be one of 3 other different data-types, I'd suggest making a wrapper class that implements Parcelable that stores the data for you. If you're passing this data around a lot, it will make your life much simpler.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号