Skip to content

Commit d11c4a4

Browse files
Builder: store context.getApplicationContext to prevent leaks.
1 parent 8b4e96b commit d11c4a4

File tree

1 file changed

+9
-1
lines changed

1 file changed

+9
-1
lines changed

objectbox-java/src/main/java/io/objectbox/BoxStoreBuilder.java

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,7 +178,7 @@ public BoxStoreBuilder androidContext(Object context) {
178178
if (context == null) {
179179
throw new NullPointerException("Context may not be null");
180180
}
181-
this.context = context;
181+
this.context = getApplicationContext(context);
182182

183183
File baseDir = getAndroidBaseDir(context);
184184
if (!baseDir.exists()) {
@@ -195,6 +195,14 @@ public BoxStoreBuilder androidContext(Object context) {
195195
return this;
196196
}
197197

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+
198206
/**
199207
* Pass a custom ReLinkerInstance, for example {@code ReLinker.log(logger)} to use for loading the native library
200208
* on Android devices. Note that setting {@link #androidContext(Object)} is required for ReLinker to work.

0 commit comments

Comments
 (0)