How to send an object from one Android Activity to another using Intents?

后端 未结 30 3605
-上瘾入骨i
-上瘾入骨i 2020-11-21 04:47

How can I pass an object of a custom type from one Activity to another using the putExtra() method of the class Intent?

30条回答
  •  天涯浪人
    2020-11-21 05:19

    You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.

    In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.

    If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

提交回复
热议问题