Created
March 30, 2014 11:25
-
-
Save Tobiaqs/9871404 to your computer and use it in GitHub Desktop.
This class allows you to preserve Objects in activities after recreation.
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
/** | |
* Allows preservation of non-context objects after i.e. rotation of the device. | |
* | |
* Usage: | |
* | |
* // Wrapper for this instance. | |
* private final ObjectStoreWrapper objects = new ObjectStoreWrapper(1); | |
* | |
* // Save a random Object, put the ID returned by the ObjectStore in the Bundle. | |
* public void onSaveInstanceState(Bundle outState) { | |
* outState.putInt("object", objects.store(new Object())); | |
* } | |
* | |
* public void onCreate(Bundle savedInstanceState) { | |
* super.onCreate(savedInstanceState); | |
* if(savedInstanceState != null) { | |
* // ID of the stored Object. | |
* int storeID = savedInstanceState.getInt("object"); | |
* | |
* // Grab the object from the ObjectStore. | |
* Object o = objects.get(storeID); | |
* } | |
* } | |
*/ | |
import android.util.SparseArray; | |
public class ObjectStore { | |
private static SparseArray<SparseArray<Object>> store = new SparseArray<SparseArray<Object>>(); | |
public static int store(int instance, Object object) { | |
final SparseArray<Object> list = instance(instance); | |
int i = 0; | |
while(list.get(i) != null) { | |
i++; | |
} | |
list.put(i, object); | |
return i; | |
} | |
public static void remove(int instance, int id) { | |
instance(instance).remove(id); | |
} | |
public static void clear(int instance) { | |
instance(instance).clear(); | |
} | |
public static Object get(int instance, int id) { | |
return instance(instance).get(id); | |
} | |
private static SparseArray<Object> instance(int instance) { | |
SparseArray<Object> s = store.get(instance); | |
if(s == null) { | |
s = new SparseArray<Object>(); | |
store.put(instance, s); | |
} | |
return s; | |
} | |
public static class ObjectStoreWrapper { | |
final int instance; | |
public ObjectStoreWrapper(int instance) { | |
this.instance = instance; | |
} | |
public int store(Object object) { | |
return ObjectStore.store(instance, object); | |
} | |
public Object get(int id) { | |
return ObjectStore.get(instance, id); | |
} | |
public void remove(int id) { | |
ObjectStore.remove(instance, id); | |
} | |
public void clear() { | |
ObjectStore.clear(instance); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment