Advertisement
Guest User

Untitled

a guest
Sep 1st, 2014
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.16 KB | None | 0 0
  1. @Override
  2. protected void setUp() {
  3. // TODO Auto-generated method stub
  4. try {
  5. super.setUp();
  6. } catch (Exception e) {
  7. // TODO Auto-generated catch block
  8. e.printStackTrace();
  9. }
  10. ObjectGraph.create(new TestModule()).inject(this);
  11. this.activity = super.getActivity();
  12. }`
  13.  
  14. public class GraphHolder {
  15.  
  16. private static GraphHolder sInstance;
  17.  
  18. private Object[] mModules;
  19. private ObjectGraph mGraph;
  20.  
  21. private GraphHolder() {
  22. }
  23.  
  24. public static GraphHolder getInstance() {
  25. if (sInstance == null) {
  26. sInstance = new GraphHolder();
  27. }
  28.  
  29. return sInstance;
  30. }
  31.  
  32. public void inject(Object object) {
  33. if (mGraph == null) {
  34. create();
  35. }
  36.  
  37. mGraph.inject(object);
  38. }
  39.  
  40. public <T> T get(Class<T> type) {
  41. if (mGraph == null) {
  42. create();
  43. }
  44.  
  45. return mGraph.get(type);
  46. }
  47.  
  48. public void addModules(Object... modules) {
  49. if (mGraph != null) {
  50. mGraph.plus(modules);
  51. } else {
  52. if (mModules == null) {
  53. mModules = modules;
  54. } else {
  55. mModules = concatenate(mModules, modules);
  56. }
  57. }
  58. }
  59.  
  60. private void create() {
  61. mGraph = ObjectGraph.create(mModules);
  62. mModules = null;
  63. }
  64.  
  65. private Object[] concatenate(Object[] a, Object[] b) {
  66. int aLength = a.length;
  67. int bLength = b.length;
  68.  
  69. Object[] c = new Object[aLength + bLength];
  70. System.arraycopy(a, 0, c, 0, aLength);
  71. System.arraycopy(b, 0, c, aLength, bLength);
  72.  
  73. return c;
  74. }
  75. }
  76.  
  77. public class MyApplication extends Application {
  78.  
  79. @Override
  80. public void onCreate() {
  81. super.onCreate();
  82. GraphHolder.getInstance().addModules(getModules());
  83. }
  84.  
  85. Object[] getModules() {
  86. return new Object[]{
  87. // your modules here
  88. };
  89. }
  90. }
  91.  
  92. @Inject Foo mFoo;
  93.  
  94. @Override
  95. public void setUp() {
  96. super.setUp();
  97. GraphHolder.getInstance().addModules(new FooModule());
  98. GraphHolder.getInstance().inject(this);
  99. getActivity(); // This is when the object graph will be created
  100. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement