Search code examples
androidkotlinserializationparcelable

How do you serialize a Parcelable to a String in Kotlin?


I'm writing an Android app in Kotlin and want to store a Location type into SQLite as a string. A Location is a Parcelable. Does a Parcelable have a method to serialize to a String?

I want to do something like this:

var loc:Location
var str:Sring

... Code to Initialize 'loc'...

str = loc.serilizeToString()

Solution

  • You can convert the object to a Parcel and then get the bytes (by calling Parcel.marshall()) and convert those to a String and store that, but you would be relying on the internal implementation of Location. A better approach would be to write your own method that serializes the data that you need from the Location object into a String. For example, something like this:

    String s = String.format("%s|%e|%e|%f|%f",
        location.getProvider(),
        location.getLatitude(),
        location.getLongitude(),
        location.getSpeed(),
        location.getBearing()
    );
    

    When you read it back from the database, you just need to parse your String into the component parts, create a new Location object and set the individual components on it. Something like this:

    String s; // Location as String
    String[] parts = s.split("|");
    Location location = new Location(parts[0]);
    location.setLatitude(Double.valueOf(parts[1]));
    location.setLongitude(Double.valueOf(parts[2]));
    location.setSpeed(Float.valueOf(parts[3]));
    location.setBearing(Float.valueOf(parts[4]));