简体   繁体   中英

How to use a Serializable class

I'm using Backendless as a backend service, it offers a class called BackendlessUser for saving and retrieving users. I'm trying to pass a User between two activities on Android by passing it as Serializable extra:

Intent intent = new Intent(PeopleActivity.this, ConversationActivity.class);
intent.putExtra("withUser", contacts.get(position));
startActivity(intent);

Since the class BackendlessUser implements Serializable . However when I run it, it gives me this error:

java.lang.RuntimeException: Parcelable encountered IOException writing serializable object (name = com.backendless.BackendlessUser)
at android.os.Parcel.writeSerializable(Parcel.java:1468)
at android.os.Parcel.writeValue(Parcel.java:1416)
....
Caused by: java.io.NotSerializableException: java.lang.Object
....

Due to, I think, this variable:

public final class BackendlessUser implements Serializable {
    private final Map<String, Object> properties = new HashMap<String, Object>();
...

How can I solve this considering that I cannot modify the BackendlessUser class?

In Android you should use Parcelable which offers better performances compared to Serializable . For an explanation about how to implement it take a look at this answer

Also, if you need to use Parcelable on your map object, see this answer

Edit: since Object is not Parcelable though you might want to follow Alexander's answer, or, even better, use a database for data persistence

Instead of passing the object, you can save the reference to it in a singleton so that it's available between the activities.

You can extend the Application class and save there. The Application class exists all the time while your app is running and is a singleton.

public class MyApp extends Application {
  public BackendUser currentUser;
}

Then:

((MyApp)getApplication()).currentUser

You should be using Parcelable to pass objects between activities. Parcelable is Android's version of Serializable , so you use that. You can find more information on Parcelable here .

If you can't modify the backend user, your best bet would be to use Alexanders suggestion and create a Singleton instance of User . This would allow you to create/update you user from any activity.

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