Skip to content

Instantly share code, notes, and snippets.

@ncruces
Created June 7, 2018 09:58
Show Gist options
  • Save ncruces/708f623210c03b3d63d3ddfc93742478 to your computer and use it in GitHub Desktop.
Save ncruces/708f623210c03b3d63d3ddfc93742478 to your computer and use it in GitHub Desktop.
Caches a Parcelable (e.g. a Bitmap) in Parcel memory (i.e. off the heap)
package io.github.ncruces.utils;
import android.graphics.Bitmap;
import android.os.BadParcelableException;
import android.os.Parcel;
import android.os.Parcelable;
public final class CachedParcelable<T extends Parcelable> implements AutoCloseable {
private final Parcelable.Creator<T> creator;
private Parcel cache;
public CachedParcelable(Parcelable.Creator<T> creator) {
this.creator = creator;
}
public synchronized T get() {
if (cache == null) return null;
try {
cache.setDataPosition(0);
return creator.createFromParcel(cache);
} catch (BadParcelableException e) {
//
} catch (RuntimeException e) {
if (creator != Bitmap.CREATOR) throw e;
}
return null;
}
public synchronized void put(T value) {
if (cache != null) cache.recycle();
if (value == null) {
cache = null;
return;
}
try {
cache = Parcel.obtain();
value.writeToParcel(cache, 0);
} catch (RuntimeException e) {
if (creator != Bitmap.CREATOR) throw e;
}
}
@Override
public synchronized void close() {
if (cache != null) {
cache.recycle();
cache = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment