Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Created December 5, 2016 11:25
Show Gist options
  • Save scruffyfox/d105c987c72e3fa1fe7b6c59e6b71fea to your computer and use it in GitHub Desktop.
Save scruffyfox/d105c987c72e3fa1fe7b6c59e6b71fea to your computer and use it in GitHub Desktop.
Intent data passer

Basic class used to temporarily storing data to be passed between activities. As only one activity can be displayed at a time, it is reasonable to use the Activity's class name to store/retrieve data for that activity.

Usage

IntentDataHelper.getInstance().store(UsersActivity.class, getAllUsers()); // large transaction!
IntentDataHelper.getInstance().retrieve(UsersActivity.class, new TypeToken<ArrayList<User>>(){}.getClass()); // large transaction!
package cube.com.helper;
import java.util.WeakHashMap;
import lombok.Getter;
/**
* Singleton class used for passing large data sets around without having to serialise.
* This class should <b>not</b> reference any kind of context without implicitly destroying
* the object when it is done to prevent Context leaks. Be wary!
*
* @author Callum Taylor
*/
public class IntentDataHelper
{
@Getter(lazy = true) private static final IntentDataHelper instance = new IntentDataHelper();
private WeakHashMap<Class, Object> dataStore = new WeakHashMap<>();
/**
* Stores object data against a class name. Operation is destructive, if {@param className} already exists in the data store map.
*
* @param className The class to store against, use the same class name to retrieve the data back.
* @param data The data to temporarily store.
*/
public void store(Class className, Object data)
{
dataStore.put(className, data);
}
/**
* Gets the stored data object from a given className, or null if nothing was stored. Operation is destructive,
* object will be removed from data store once retrieved.
*
* @param className The class name used to originally store the data
* @return The found object or null.
*/
public Object retrieve(Class className)
{
return retrieve(className, Object.class);
}
/**
* Gets the stored data object from a given className, or null if nothing was stored. Operation is destructive,
* object will be removed from data store once retrieved.
*
* @param className The class name used to originally store the data
* @param classType The class type to force cast to
* @return The found object or null.
*/
public <T> T retrieve(Class className, Class<T> classType)
{
return (T)classType.cast(dataStore.remove(className));
}
/**
* Force destroys the data store to remove all references
*/
public void clear()
{
dataStore = new WeakHashMap<>();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment