Skip to content

Instantly share code, notes, and snippets.

@eccyan
Last active August 29, 2015 14:16
Show Gist options
  • Save eccyan/c5114344313528e4cdae to your computer and use it in GitHub Desktop.
Save eccyan/c5114344313528e4cdae to your computer and use it in GitHub Desktop.
Workaround 'Unknown state SAVING' for mortar 0.16
package mortar;
import android.os.Bundle;
import java.lang.reflect.Field;
import timber.log.Timber;
// Mortar がバグ修正を行わずにメジャーバージョンを上げたためパッチで回避
// @see https://github.com/square/mortar/pull/107
public class WrappedRealActivityScope extends RealActivityScope {
protected enum LoadingState {
IDLE, LOADING, SAVING;
private Enum<?> toParentLoadingState() {
for (Class<?> clazz : RealActivityScope.class.getDeclaredClasses()) {
if (clazz.getSimpleName().equals("LoadingState")) {
for (Enum<?> state : (Enum[]) clazz.getEnumConstants()) {
if (state.name().equals(this.name())) {
return state;
}
}
}
}
return null;
}
}
public WrappedRealActivityScope(Object scope) {
super((RealActivityScope)scope);
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
try {
final Bundle latestSavedInstanceState = getLatestSavedInstanceStaete();
if (latestSavedInstanceState != null) {
for (RealScope child : children.values()) {
if (!(child instanceof RealActivityScope)) {
continue;
}
((RealActivityScope) child).onSaveInstanceState(
getNestedBundle(child, latestSavedInstanceState, true));
}
}
setMyLoadingState(LoadingState.IDLE.toParentLoadingState());
} catch (IllegalAccessException | NoSuchFieldException e) {
Timber.e(e, "Could not save instance states.");
}
}
protected Bundle getLatestSavedInstanceStaete()
throws NoSuchFieldException, IllegalAccessException {
final Field field = RealActivityScope.class.getDeclaredField("latestSavedInstanceState");
field.setAccessible(true);
return (Bundle) field.get(this);
}
protected void setMyLoadingState(Enum<?> state)
throws IllegalAccessException, NoSuchFieldException {
final Field field = RealActivityScope.class.getDeclaredField("myLoadingState");
field.setAccessible(true);
field.set(this, state);
}
private Bundle getNestedBundle(MortarScope scope, Bundle bundle, boolean eager) {
return getNamedBundle(scope.getName(), bundle, eager);
}
private Bundle getNamedBundle(String name, Bundle bundle, boolean eager) {
if (bundle == null) {
return null;
}
Bundle child = bundle.getBundle(name);
if (eager && child == null) {
child = new Bundle();
bundle.putBundle(name, child);
}
return child;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment