Last active
August 29, 2015 14:17
-
-
Save Takhion/abf9ec3b01d3a6a2298e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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