LibGDX - load file in AssetManager from local storage - android

I have a model that is in local storage (/data/user/0/com.myapp/files/model.g3db). I want to load this model in my AssetManager to use it later.
If use standard method like assetManager.load("model.obj", Model.class);, it gets a file from the assets folder that is a part of project. It doesn't suit me. So, I tried to use AssetDescriptor to specify the file:
FileHandle fh = Gdx.files.local("model.g3db");
if(fh.exists()) Gdx.app.log("file", "exists");
else Gdx.app.log("file", "not exists");
AssetDescriptor<Model> ad = new AssetDescriptor<Model>(fh, Model.class);
assets.load(ad);
Output:
I/file: exists
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Couldn't load dependencies of asset: model.g3db
at com.badlogic.gdx.assets.AssetLoadingTask.handleAsyncLoader(AssetLoadingTask.java:121)
at com.badlogic.gdx.assets.AssetLoadingTask.update(AssetLoadingTask.java:90)
at com.badlogic.gdx.assets.AssetManager.updateTask(AssetManager.java:507)
at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:381)
at com.myapp.EngineCore.render(EngineCore.java:226) 
at com.badlogic.gdx.backends.android.AndroidGraphicsLiveWallpaper.onDrawFrame(AndroidGraphicsLiveWallpaper.java:220) 
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1571) 
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1270) 
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: com.badlogic.gdx.utils.SerializationException: Error parsing file: model.g3db
at com.badlogic.gdx.utils.async.AsyncResult.get(AsyncResult.java:46)
at com.badlogic.gdx.assets.AssetLoadingTask.handleAsyncLoader(AssetLoadingTask.java:119)
at com.badlogic.gdx.assets.AssetLoadingTask.update(AssetLoadingTask.java:90) 
at com.badlogic.gdx.assets.AssetManager.updateTask(AssetManager.java:507) 
at com.badlogic.gdx.assets.AssetManager.update(AssetManager.java:381) 
at com.nolesh.android.livewallpapers.iamrich.EngineCore.render(EngineCore.java:226) 
at com.badlogic.gdx.backends.android.AndroidGraphicsLiveWallpaper.onDrawFrame(AndroidGraphicsLiveWallpaper.java:220) 
at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1571) 
at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1270) 
Caused by: com.badlogic.gdx.utils.SerializationException: Error parsing file: model.g3db
at com.badlogic.gdx.utils.UBJsonReader.parse(UBJsonReader.java:56)
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.parseModel(G3dModelLoader.java:65)
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.loadModelData(G3dModelLoader.java:61)
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:75)
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:35)
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:64)
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:34)
at com.badlogic.gdx.utils.async.AsyncExecutor$2.call(AsyncExecutor.java:58)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
at java.lang.Thread.run(Thread.java:764)
Caused by: com.badlogic.gdx.utils.GdxRuntimeException: Error reading file: model.g3db (Internal)
at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:77)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:151)
at com.badlogic.gdx.utils.UBJsonReader.parse(UBJsonReader.java:54)
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.parseModel(G3dModelLoader.java:65) 
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.loadModelData(G3dModelLoader.java:61) 
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:75) 
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:35) 
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:64) 
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:34) 
at com.badlogic.gdx.utils.async.AsyncExecutor$2.call(AsyncExecutor.java:58) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
at java.lang.Thread.run(Thread.java:764) 
Caused by: java.io.FileNotFoundException: model.g3db
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:374)
at android.content.res.AssetManager.open(AssetManager.java:348)
at com.badlogic.gdx.backends.android.AndroidFileHandle.read(AndroidFileHandle.java:75)
at com.badlogic.gdx.files.FileHandle.read(FileHandle.java:151) 
at com.badlogic.gdx.utils.UBJsonReader.parse(UBJsonReader.java:54) 
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.parseModel(G3dModelLoader.java:65) 
at com.badlogic.gdx.graphics.g3d.loader.G3dModelLoader.loadModelData(G3dModelLoader.java:61) 
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:75) 
at com.badlogic.gdx.assets.loaders.ModelLoader.getDependencies(ModelLoader.java:35) 
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:64) 
at com.badlogic.gdx.assets.AssetLoadingTask.call(AssetLoadingTask.java:34) 
at com.badlogic.gdx.utils.async.AsyncExecutor$2.call(AsyncExecutor.java:58) 
at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636) 
at java.lang.Thread.run(Thread.java:764) 
When I move this model to the assets folder of my project, it successfully loads.
So, my question is how to load model to the AssetManager from the local storage.

It's not a perfect solution, but it works. AssetManager has a constructor that accepts FileHandleResolver as a parameter.
AssetManager assets = new AssetManager(new LocalFileHandleResolver());
It's not an ideal solution, because if you are going to use mixed assets from the local storage and the internal one, that you need to create AssetManager for each one.

Related

long SVG Asset file error : R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE

I'm having some problems with Android Studio at the moment because I recently started using "Vector Assets". I've done absolutely everything necessary to display them correctly in my application (using the app:srcCompat="" in the xml, android {defaultConfig {vectorDrawables.useSupportLibrary true}} in the build.gradle, and AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); in the onCreate() method before setContentView()).
The svg files I imported into Android Studio do not have errors themselves, I can see the result without any problem in an ImageView with the wizard. The only problem comes when I run my application and it arrives at the time to draw the svg. Some of my svg's still work, while others don't, so I think some of them take too long to process.
Here is the error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.retroverse.bataille_corse, PID: 18807
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.retroverse.bataille_corse/com.retroverse.bataille_corse.MenuPrincipal}: android.view.InflateException: Binary XML file line #127: Binary XML file line #127: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2985)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3120)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1840)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: android.view.InflateException: Binary XML file line #127: Binary XML file line #127: Error inflating class ImageView
Caused by: android.view.InflateException: Binary XML file line #127: Error inflating class ImageView
Caused by: android.content.res.Resources$NotFoundException: Drawable com.retroverse.bataille_corse:drawable/card_49_en with resource ID #0x7f060099
Caused by: android.content.res.Resources$NotFoundException: File res/drawable/card_49_en.xml from drawable resource ID #0x7f060099
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:854)
at android.content.res.ResourcesImpl.loadDrawable(ResourcesImpl.java:634)
at android.content.res.MiuiResourcesImpl.loadDrawable(MiuiResourcesImpl.java:329)
at android.content.res.Resources.getDrawableForDensity(Resources.java:902)
at android.content.res.Resources.getDrawable(Resources.java:841)
at android.content.Context.getDrawable(Context.java:644)
at androidx.core.content.ContextCompat.getDrawable(ContextCompat.java:454)
at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:144)
at androidx.appcompat.widget.ResourceManagerInternal.getDrawable(ResourceManagerInternal.java:132)
at androidx.appcompat.content.res.AppCompatResources.getDrawable(AppCompatResources.java:104)
at androidx.appcompat.widget.AppCompatImageHelper.loadFromAttributes(AppCompatImageHelper.java:59)
at androidx.appcompat.widget.AppCompatImageView.<init>(AppCompatImageView.java:78)
at androidx.appcompat.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at androidx.appcompat.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:187)
at androidx.appcompat.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:107)
at androidx.appcompat.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1407)
at androidx.appcompat.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1457)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:776)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:734)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:867)
at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:828)
at android.view.LayoutInflater.inflate(LayoutInflater.java:519)
at android.view.LayoutInflater.inflate(LayoutInflater.java:427)
at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:161)
at com.retroverse.bataille_corse.MenuPrincipal.onCreate(MenuPrincipal.java:24)
at android.app.Activity.performCreate(Activity.java:7232)
E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:7221)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2965)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3120)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1840)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6872)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE
at android.util.PathParser.nCreatePathDataFromString(Native Method)
at android.util.PathParser.access$200(PathParser.java:24)
at android.util.PathParser$PathData.<init>(PathParser.java:76)
at android.graphics.drawable.VectorDrawable$VFullPath.updateStateFromTypedArray(VectorDrawable.java:2016)
at android.graphics.drawable.VectorDrawable$VFullPath.inflate(VectorDrawable.java:1967)
at android.graphics.drawable.VectorDrawable.inflateChildElements(VectorDrawable.java:819)
at android.graphics.drawable.VectorDrawable.inflate(VectorDrawable.java:717)
at android.graphics.drawable.DrawableInflater.inflateFromXmlForDensity(DrawableInflater.java:142)
at android.graphics.drawable.Drawable.createFromXmlInnerForDensity(Drawable.java:1332)
at android.graphics.drawable.Drawable.createFromXmlForDensity(Drawable.java:1291)
at android.content.res.ResourcesImpl.createFromXmlForDensity(ResourcesImpl.java:1506)
at android.content.res.ResourcesImpl.loadDrawableForCookie(ResourcesImpl.java:838)
... 41 more
The most important line, I think, is Caused by: java.lang.IllegalArgumentException: R is not a valid verb. Failure occurred at position 2 of path: STRING_TOO_LARGE.
We also know that this svg was caught in the middle (its size is 187 kilobytes). So I think my SVG file (even imported in Android Studio by "Vector Asset") is too heavy.
As we are told here, the STRING_TOO_LARGE issue appears when the string "is longer than 0x7FFF = 32767 characters". (In the reproduction part)
Indeed, the only svg to work in my application are lighter than 32 kb, which could explain this.
But I really need to display this svg (don't offer to convert it to png!) correctly, and if possible without optimizing its paths.
Any help would be welcome!
I found the answer (at last...).
Actually, there is no real problem with Vector Assets over 32 kb, it all depends on what is in the code. I should have paid more attention to the warnings than usual I don't always look at...
I discovered inside my svg a path data with a path of more than 40kb (in one string so). The fact is that, according to the site in the question, a String can't have more than (about) 32k characters or the whole string used in any xml file will be replaced by "STRING_TOO_LARGE". Anyway, by just removing this line here, I can draw the vector perfectly well (while it is still 250 kb, but now incomplete).
What's quite surprising is that Android Studio only displays a warning (where the string is longer than 32k characters) just to make me understand that an svg with a long path can be slow to display, instead of warning me that the path will be corrupted because it's too long (or even better turn this warning into an error in the IDE, to avoid an unpleasant surprise).
Thanks to #TheBigBadBoy I splitted long SVG path into several segments. I opened XML file of the image and divided the path by M symbol (see also how to split one path into two paths in svg).
<path
android:fillColor="#ffffff"
android:fillType="evenOdd"
android:pathData="M40.255,47.8897C40.1686, ... ,47.8897ZM38.7713,40.2642L38.8362, ..., 46.0978Z"
/>
You can see that each segment starts with M and ends with Z. You can retain about 20Kb in the first path and cut the tail. Then paste the tail into the second path. Make so many paths that all of them become less than 32 Kb.
So, you will get:
<path
android:fillColor="#ffffff"
android:fillType="evenOdd"
android:pathData="M40.255,47.8897C40.1686, ... ,47.8897Z"
/>
<path
android:fillColor="#ffffff"
android:fillType="evenOdd"
android:pathData="M38.7713,40.2642L38.8362, ..., 46.0978Z"
/>

ArCore .obj FileNotFound exception

I am making an ArCore app and when I build my ModelRenderable I am getting this exception thrown:
java.util.concurrent.CompletionException: java.io.FileNotFoundException: Coffee Cup_final.obj (No such file or directory)
at com.google.ar.sceneform.utilities.SceneformBufferUtils.inputStreamToByteBuffer(SourceFile:49)
at com.google.ar.sceneform.rendering.LoadRenderableFromSfbTask.lambda$downloadAndProcessRenderable$0$LoadRenderableFromSfbTask(LoadRenderableFromSfbTask.java:119)
at com.google.ar.sceneform.rendering.-$$Lambda$LoadRenderableFromSfbTask$0DkaOpfpmr8DYlbaxWogZtUpKTw.get(Unknown Source:4)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1625)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: java.io.FileNotFoundException: Coffee Cup_final.obj (No such file or directory)
at java.io.FileInputStream.open0(Native Method)
But I can see this file exists. Here is the renderable followed by build gradle.
ModelRenderable.builder()
.setSource(this, Uri.parse("Coffee Cup_final.obj.obj"))
.build()
.thenAccept(this::onRenderableLoaded)
.exceptionally(throwable -> {
Log.i("Sceneform", "failed to load model");
return null;
});
sceneform.asset('sampledata/Coffee Cup_final.obj.obj',
'default',
'sampledata/Coffee Cup_final.obj.sfa',
'src/main/assets/Coffee Cup_final.obj')
Does it have to do with the uppercase naming of my 3D object?
The sceneform.asset() step in build.gradle converts the OBJ file to Sceneform's internal SFB file format. So the file that's created and copied to your assets folder is src/main/assets/Coffee Cup_final.obj.sfb . So if you change
ModelRenderable.builder().setSource(this, Uri.parse("Coffee Cup_final.obj.obj"))
to
ModelRenderable.builder().setSource(this, Uri.parse("Coffee Cup_final.obj.sfb"))
it should work.

Android-Native library (com/sun/jna/android-x86/libjnidispatch.so) not found in resource path (.)

I am developing my android App with MongoDB Stitch, which has a pre-requisite that I need to install MongoDB Mobile Tarball.Installation Structure
After installation I run the program, getting this exception:
08-09 13:01:34.308 20251-20278/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: io.datats.datatungshing.app, PID: 20251
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:354)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
at java.util.concurrent.FutureTask.run(FutureTask.java:271)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:764)
Caused by: com.mongodb.embedded.client.MongoClientEmbeddedException: Failed to load the mongodb library: 'mongo_embedded_capi'.
Native library (com/sun/jna/android-x86/libjnidispatch.so) not found in resource path (.)
Please set the library location by either:
- Adding it to the classpath.
- Setting 'jna.library.path' system property
- Configuring it in the 'MongoEmbeddedSettings.builder().libraryPath' method.
at com.mongodb.embedded.client.MongoDBCAPIHelper.init(MongoDBCAPIHelper.java:60)
at com.mongodb.embedded.client.MongoClients.init(MongoClients.java:38)
at com.mongodb.stitch.core.services.mongodb.local.internal.CoreLocalMongoDbService.getClient(CoreLocalMongoDbService.java:36)
at com.mongodb.stitch.android.services.mongodb.local.LocalMongoDbService.access$000(LocalMongoDbService.java:35)
at com.mongodb.stitch.android.services.mongodb.local.LocalMongoDbService$1.getClient(LocalMongoDbService.java:50)
at com.mongodb.stitch.android.services.mongodb.local.LocalMongoDbService$1.getClient(LocalMongoDbService.java:41)
at com.mongodb.stitch.android.core.internal.StitchAppClientImpl.getServiceClient(StitchAppClientImpl.java:105)
at io.datats.datatungshing.forboledts.SecondActivity$getTrendFromDB.doInBackground(SecondActivity.java:57)
at io.datats.datatungshing.forboledts.SecondActivity$getTrendFromDB.doInBackground(SecondActivity.java:37)
at android.os.AsyncTask$2.call(AsyncTask.java:333)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
... 4 more
Caused by: java.lang.UnsatisfiedLinkError: Native library (com/sun/jna/android-x86/libjnidispatch.so) not found in resource path (.)
at com.sun.jna.Native.loadNativeDispatchLibraryFromClasspath(Native.java:962)
at com.sun.jna.Native.loadNativeDispatchLibrary(Native.java:922)
at com.sun.jna.Native.<clinit>(Native.java:190)
at com.sun.jna.Native.loadLibrary(Native.java:544)
at com.mongodb.embedded.client.MongoDBCAPIHelper.init(MongoDBCAPIHelper.java:58)
... 14 more
The highlighted code is in my AsyncTask, which is just creating a MongoClient in my java program:
final StitchAppClient client =
Stitch.initializeDefaultAppClient("APP-ID");
final MongoClient mobileClient =
client.getServiceClient(LocalMongoDbService.clientFactory);
MongoCollection<Document> localCollection =
mobileClient.getDatabase(databaseName).getCollection("CollectionName");
/*Document doc = localCollection.find().first();
this.keywordList = (List<String>) doc.get("list");*/
return true;
I have also created and included a jniLibs directory in my src/main/, which contains the following components:
jniLibs
In my jniLibs I also have the file libjnidispatch.io included. Please help me on this strange bug. The emulator I used is Nexus 6 API 28. Thank you!!!

Android studio trying to connect to mongodb using AsyncTask throwing an error exception

MongoCredential credential = MongoCredential.createCredential(user, database, password);
MongoClientOptions options = MongoClientOptions.builder().sslEnabled(true).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential), options);
throwing the following error
Failed to get process identifier from JMX, using random number instead
java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/management/ManagementFactory;
at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506)
at org.bson.types.ObjectId.<clinit>(ObjectId.java:464)
at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69)
at com.mongodb.Mongo.createCluster(Mongo.java:683)
at com.mongodb.Mongo.createCluster(Mongo.java:669)
at com.mongodb.Mongo.<init>(Mongo.java:282)
at com.mongodb.MongoClient.<init>(MongoClient.java:187)
at com.example.michael.version_10.Connection.doInBackground(Connection.java:40)
at com.example.michael.version_10.Connection.doInBackground(Connection.java:30)
at android.os.AsyncTask$2.call(AsyncTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[zip file "/data/app/com.example.michael.version_10-1/base.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_dependencies_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_0_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_1_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_2_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_3_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_4_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_5_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_6_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_7_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_8_apk.apk", zip file "/data/app/com.example.michael.version_10-1/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/com.example.michael.version_10-1/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at org.bson.types.ObjectId.createProcessIdentifier(ObjectId.java:506) 
at org.bson.types.ObjectId.<clinit>(ObjectId.java:464) 
at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47) 
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:69) 
at com.mongodb.Mongo.createCluster(Mongo.java:683) 
at com.mongodb.Mongo.createCluster(Mongo.java:669) 
at com.mongodb.Mongo.<init>(Mongo.java:282) 
at com.mongodb.MongoClient.<init>(MongoClient.java:187) 
at com.example.michael.version_10.Connection.doInBackground(Connection.java:40) 
at com.example.michael.version_10.Connection.doInBackground(Connection.java:30) 
at android.os.AsyncTask$2.call(AsyncTask.java:305) 
at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
I was actually doing it the wrong way. It is not advisable to connect to MongoDB directly it is recommended to use an Rest API. And that solved my problem.

Using android internal storage for images

I am trying to save the image file into my application's internal storage.
To do this, I wrote the following method which takes the id and bitmap and creates the file of an image, where directory is the class static field of type File.
// Returns thumbnail
private static Bitmap saveBitmapWithThumbnail(long id, Bitmap bitmap) {
Bitmap thumbnail;
if(directory == null) {
ContextWrapper cw = new ContextWrapper(Engine.getContext());
directory = cw.getDir(DIRECTORY_NAME, Context.MODE_PRIVATE);
if(!directory.exists()) directory.mkdir();
}
saveBitmap(getImageFileName(id), bitmap);
saveBitmap(getThumbnailFileName(id), thumbnail=makeThumbnail(bitmap));
return thumbnail;
}
What this method does is to get an id and bitmap and save it's original file and created thumbnail into the internal storage.
The names are generated as [id+".png"] for the original file and [id+"_tn.png"] for the thumbnail file.
saveBitmap() mehtod is the one which is writing the bitmap to the internal storage.
private static void saveBitmap(String fileName, Bitmap bitmap) {
File imageFile = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
} catch(Exception e) {}
}
It takes the file name (11.png, 11_tn.png, ...) and the bitmap (whether it's original or thumbnail) and makes a file and compress into it's outputstream.
The weird thing is that when I run my application for the first time saving the images, it works great.
It can read and write the images that are stored int the internal storage.
However, after I close my application and run it again, it throws FileNotFoundException with following logs.
W/System.err: java.io.FileNotFoundException: /1.png: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:458)
W/System.err: at java.io.FileInputStream.<init>(FileInputStream.java:78)
W/System.err: at com.google.dotplace.dotplace.data.Image.parseCursor(Image.java:118)
W/System.err: at com.google.dotplace.dotplace.data.Image.checkDebug(Image.java:74)
W/System.err: at com.google.dotplace.dotplace.LoadActivity.debugDatabase(LoadActivity.java:77)
W/System.err: at com.google.dotplace.dotplace.LoadActivity.onCreate(LoadActivity.java:25)
W/System.err: at android.app.Activity.performCreate(Activity.java:5275)
W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2167)
W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2253)
W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:142)
W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1203)
W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
W/System.err: at android.os.Looper.loop(Looper.java:136)
W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5120)
W/System.err: at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err: at java.lang.reflect.Method.invoke(Method.java:515)
W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
W/System.err: at dalvik.system.NativeStart.main(Native Method)
W/System.err: Caused by: libcore.io.ErrnoException: open failed: ENOENT (No such file or directory)
W/System.err: at libcore.io.Posix.open(Native Method)
W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:110)
W/System.err: at libcore.io.IoBridge.open(IoBridge.java:442)
W/System.err: ... 19 more
Only conclusion I can make is that internal storage changes or it's files are delete after my application is closed, but I don't know why.
What I am guessing now is that I have problem with my testing.
I'm testing this as follows.
Compile and run the project with file insertions and check.
Compile and run the project without file insertions and check if 1's data is remaining.
I am doing this because I did't make any ui of writing or reading files in my app.
My only guess is when I compile the project again, it somehow changes something unique in the context of my application which leads to changed internal storage which I think it's quite nonsense.
Where am I wrong??
There are several things which you may be doing wrong. Whenever you want to read/write internal/external storage, you have to make sure you do the following things;
Put READ/WRITE Storage permissions in your Manifest.
If your Android Version is Marshmallow or greater, ask run-time permissions. You can get information about this here
Make sure the path is correct. Most of the time hard-coded paths make difference. Refer here for more detail.
Make sure you call mkdirs() if directory doesn't exist.
Make sure the filename is correct. You said earlier that it's 11.png and 11_tn.png but later you accessed 1.png. May be this is causing a problem.
you have to give runtime permission for marshmallow and above:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />`

Categories

Resources