Skip to content

Instantly share code, notes, and snippets.

@Takhion Takhion/MapSerializer.java
Last active Aug 29, 2015

Embed
What would you like to do?
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Map;
public class MapSerializer {
private MapSerializer() {}
@NonNull
public static <T extends Map & Serializable> Intent putMapExtra(
@NonNull Intent intent, @NonNull String name, @NonNull T map)
throws IOException {
return intent.putExtra(name, serializeMap(map));
}
@Nullable
public static <T extends Map & Serializable> T getMapExtra(
@NonNull Intent intent, @NonNull String name)
throws IOException, ClassNotFoundException, ClassCastException {
final byte[] serializedMap = intent.getByteArrayExtra(name);
//noinspection unchecked
return serializedMap == null ? null : deserializeMap(serializedMap);
}
@NonNull
public static <T extends Map & Serializable> byte[] serializeMap(@NonNull T map)
throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(map);
return bos.toByteArray();
}
finally {
try {
if (out != null) {
out.close();
}
}
catch (IOException ignore) {}
try {
bos.close();
}
catch (IOException ignore) {}
}
}
@NonNull
public static <T extends Map & Serializable> T deserializeMap(@NonNull byte[] serializedMap)
throws IOException, ClassNotFoundException, ClassCastException {
ByteArrayInputStream bis = new ByteArrayInputStream(serializedMap);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
//noinspection unchecked
return (T)in.readObject();
} finally {
try {
bis.close();
}
catch (IOException ignore) {}
try {
if (in != null) {
in.close();
}
}
catch (IOException ignore) {}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.