Skip to content

Commit 8ccbbf4

Browse files
committed
getAndroidFilesDir: workaround for race condition in Android before 4.4
1 parent fdf0656 commit 8ccbbf4

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

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

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,8 @@ public BoxStoreBuilder androidContext(Object context) {
148148
if (context == null) {
149149
throw new NullPointerException("Context may not be null");
150150
}
151-
File baseDir = new File(getAndroidFilesDir(context), "objectbox");
151+
File filesDir = getAndroidFilesDir(context);
152+
File baseDir = new File(filesDir, "objectbox");
152153
if (!baseDir.exists()) {
153154
boolean ok = baseDir.mkdirs();
154155
if (!ok) {
@@ -169,12 +170,16 @@ private File getAndroidFilesDir(Object context) {
169170
try {
170171
Method getFilesDir = context.getClass().getMethod("getFilesDir");
171172
filesDir = (File) getFilesDir.invoke(context);
173+
if (filesDir == null) {
174+
// Race condition in Android before 4.4: https://issuetracker.google.com/issues/36918154 ?
175+
System.err.println("getFilesDir() returned null - retrying once...");
176+
filesDir = (File) getFilesDir.invoke(context);
177+
}
172178
} catch (Exception e) {
173179
throw new RuntimeException(
174180
"Could not init with given Android context (must be sub class of android.content.Context)", e);
175181
}
176182
if (filesDir == null) {
177-
// TODO should we consider https://issuetracker.google.com/issues/36918154 ?
178183
throw new IllegalStateException("Android files dir is null");
179184
}
180185
return filesDir;
@@ -190,6 +195,7 @@ private File getAndroidFilesDir(Object context) {
190195
* For highly concurrent setups (e.g. you are using ObjectBox on the server side) it may make sense to increase the
191196
* number.
192197
*/
198+
193199
public BoxStoreBuilder maxReaders(int maxReaders) {
194200
this.maxReaders = maxReaders;
195201
return this;

0 commit comments

Comments
 (0)