GeezerVison is showing github.com — Builder: store context.getApplicationContext to prevent leaks. · mimoccc/objectbox-java@d11c4a4
File tree
Expand file treeCollapse file tree
Open diff view settings
objectbox-java/src/main/java/io/objectbox
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboardExpand all lines: objectbox-java/src/main/java/io/objectbox/BoxStoreBuilder.java +9-1Lines changed: 9 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -178,7 +178,7 @@ public BoxStoreBuilder androidContext(Object context) { |
178 | 178 | if (context == null) { |
179 | 179 | throw new NullPointerException("Context may not be null"); |
180 | 180 | } |
181 | | - this.context = context; |
| 181 | + this.context = getApplicationContext(context); |
182 | 182 |
|
183 | 183 | File baseDir = getAndroidBaseDir(context); |
184 | 184 | if (!baseDir.exists()) { |
@@ -195,6 +195,14 @@ public BoxStoreBuilder androidContext(Object context) { |
195 | 195 | return this; |
196 | 196 | } |
197 | 197 |
|
| 198 | + private Object getApplicationContext(Object context) { |
| 199 | + try { |
| 200 | + return context.getClass().getMethod("getApplicationContext").invoke(context); |
| 201 | + } catch (ReflectiveOperationException e) { |
| 202 | + throw new RuntimeException("context must be a valid Android Context", e); |
| 203 | + } |
| 204 | + } |
| 205 | + |
198 | 206 | /** |
199 | 207 | * Pass a custom ReLinkerInstance, for example {@code ReLinker.log(logger)} to use for loading the native library |
200 | 208 | * on Android devices. Note that setting {@link #androidContext(Object)} is required for ReLinker to work. |
|