There's a lot of posts about this problem, but noone seems to work, so maby some things have changed.
I am trying to connect my android application to a MongoDB server located on mLab. I'm using Mongo Java Drived and have off course added the library to android studio.
It is possible to start the app, but when I click on the register button the application craches.
Here's my code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.bson.Document;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText username = (EditText)findViewById(R.id.username);
final Button bRegister = (Button) findViewById(R.id.bRegister);
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringUsername = username.toString();
try {
addToDatabase(stringUsername);
} catch(Exception e) {
e.printStackTrace();
}
}
});
}
private static void addToDatabase(String username){
MongoClientURI uri = new MongoClientURI("mongodb:///*mLab database URL */");
MongoClient client = new MongoClient(uri);
MongoDatabase db = client.getDatabase(uri.getDatabase());
MongoCollection<Document> coll = db.getCollection("newDB");
Document doc = new Document("username", username);
coll.insertOne(doc);
client.close();
}
}
I also have permision.INTERNET in the manifest file.
Any help would be very appreciated!
//Edit
Stacktrace:
03/10 02:43:09: Launching app
Cold swapped changes.
$ adb shell am start -n "com.newhdc.pedergb.mongodb_servertester/com.newhdc.pedergb.mongodb_servertester.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 4752 on device emulator-5554
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
W/org.bson.ObjectId: 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:533)
at org.bson.types.ObjectId.<clinit>(ObjectId.java:491)
at com.mongodb.connection.ClusterId.<init>(ClusterId.java:47)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:105)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.management.ManagementFactory" on path: DexPathList[[dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-support-annotations-25.1.0_11ac1b6ae4b8623fca16868c12f685674e962f99-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_9-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_8-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_7-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_6-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_4-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_3-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_2-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_1-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-slice_0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-core-3.4.2_cf1ecbf321a58b8bf97e118b2c0ff7614ac982a5-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-mongodb-driver-3.4.2_cfefe7ed281d321e57736b38e1e68fc6160680ac-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-vector-drawable-25.1.0_3dbe341ffa762dac2cc1137bc6aae1731f3bc1c0-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-v4-25.1.0_c534a46cb17b55c593319a94e0d90e0b75103a24-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-media-compat-25.1.0_b58e3876df91b49420cb0766dd6edfdbff0dedbc-classes.dex", dex file "/data/data/com.newhdc.pedergb.mongodb_servertester/files/instant-run/dex/slice-com.android.support-support-fragment-25.1.0_d616629f11d994c207dfc4b5d01648e3194bccbc-classes.dex", dex f
I/cluster: Cluster created with settings {hosts=[ds123080.mlab.com:23080], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500}
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: **FATAL EXCEPTION**: main
Process: com.newhdc.pedergb.mongodb_servertester, PID: 4752
java.lang.ExceptionInInitializerError
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.security.CodeSource java.security.ProtectionDomain.getCodeSource()' on a null object reference
at com.mongodb.connection.ClientMetadataHelper.getDriverVersion(ClientMetadataHelper.java:111)
at com.mongodb.connection.ClientMetadataHelper.getDriverInformation(ClientMetadataHelper.java:201)
at com.mongodb.connection.ClientMetadataHelper.addDriverInformation(ClientMetadataHelper.java:182)
at com.mongodb.connection.ClientMetadataHelper.<clinit>(ClientMetadataHelper.java:64)
at com.mongodb.connection.InternalStreamConnectionFactory.<init>(InternalStreamConnectionFactory.java:41)
at com.mongodb.connection.DefaultClusterableServerFactory.create(DefaultClusterableServerFactory.java:68)
at com.mongodb.connection.BaseCluster.createServer(BaseCluster.java:360)
at com.mongodb.connection.SingleServerCluster.<init>(SingleServerCluster.java:54)
at com.mongodb.connection.DefaultClusterFactory.create(DefaultClusterFactory.java:114)
at com.mongodb.Mongo.createCluster(Mongo.java:744)
at com.mongodb.Mongo.createCluster(Mongo.java:728)
at com.mongodb.Mongo.createCluster(Mongo.java:702)
at com.mongodb.Mongo.<init>(Mongo.java:310)
at com.mongodb.Mongo.<init>(Mongo.java:306)
at com.mongodb.MongoClient.<init>(MongoClient.java:284)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.addToDatabase(MainActivity.java:39)
at com.newhdc.pedergb.mongodb_servertester.MainActivity.access$000(MainActivity.java:14)
at com.newhdc.pedergb.mongodb_servertester.MainActivity$1.onClick(MainActivity.java:29)
at android.view.View.performClick(View.java:5637)
at android.view.View$PerformClick.run(View.java:22429)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Application terminated.
Unfortunately, the Mongo Java Driver does not work on Android, as Android is missing some Java classes, according to this StackOverflow post. However, a kind StackOverflow user has forked the Mongo Java Driver and fixed the issue. You can see their version of the library on Github.
Scroll down to the description and download the latest jar file. Right now, it's this one:
https://github.com/matfur92/mongo-java-driver/blob/gh-pages/JARs/mongo-java-driver-3.4.0-SNAPSHOT.jar?raw=true.
Next, go ahead and delete the line in your build.gradle dependencies for mongo-java-driver. The line to delete should look something like this:
dependencies {
...
compile 'org.mongodb:mongodb-driver:3.4.2'
...
}
Finally, add the jar you downloaded to your application (guide here). Now your code should work without modification. I was able to use regular MongoDB functionality just fine, but I was not able to get GridFS to work.
I had the same issue.
Indeed problem is that you call the connection in the main thread.
add the following to the onCreate method.
#Override
protected void onCreate(Bundle savedInstanceState) {
if (android.os.Build.VERSION.SDK_INT > 9)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Hope that helps.
Related
Issue:
I am getting the following error:
java.lang.IllegalArgumentException: No available camera can be found.
when calling and instance method ProcessCameraProvider.bindToLifecycle(). See this in the context of the code below by searching for "------ Code Crashes Here --------------".
Question:
How do I prevent this error and subsequent crashing of the app? More specifically, how do I ensure the CameraSelector can return a camera instance for the Nexus 6?
Hypothesis
It appears there is something wrong with the CameraSelector used in this call. If I set a breakpoint on the bindToLifecycle line, and debug up to that point and add a watch for `cameraProvider.hasCamera(cameraSelector) it returns false. Maybe this is not intended to return true until the bindToLifecycle method has been called. If so, how can I verify the cameraSelector object has been created sucessfully (successfully meaning it points to an actual camera object)?
In the creation of the cameraSelector object, I use the requireLensFacing method in the builder, so it appears the Nexus 6 hardware does not tag anything with these LENS_FACING_BACK or LENS_FACING_FRONT and therefore does not return any camera instance? Do I understand this correctly?
I should note that this error did not occur when the exact same code was run on a Nexus 5, which is why I am inclined to think it is a hardware issue.
I also tried the LENS_FACING_FRONT int, but had the same error. If I remove the requireLensFacing build component altogether I get a different error:
java.util.NoSuchElementException
Code
package jp.oist.cameraxapp;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.camera.core.Camera;
import androidx.camera.core.CameraSelector;
import androidx.camera.core.ImageAnalysis;
import androidx.camera.core.ImageCapture;
import androidx.camera.core.ImageProxy;
import androidx.camera.core.Preview;
import androidx.camera.lifecycle.ProcessCameraProvider;
import androidx.camera.view.PreviewView;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.LifecycleOwner;
import android.os.Bundle;
import android.util.Log;
import android.util.Size;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MainActivity extends AppCompatActivity {
private ListenableFuture<ProcessCameraProvider> cameraProviderFuture;
private ExecutorService executor;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
executor = Executors.newSingleThreadExecutor();
PreviewView previewView = findViewById(R.id.previewView);
cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
try {
// Camera provider is now guaranteed to be available
ProcessCameraProvider cameraProvider = cameraProviderFuture.get();
// Set up the view finder use case to display camera preview
Preview preview = new Preview.Builder().build();
// Choose the camera by requiring a lens facing
CameraSelector cameraSelector = new CameraSelector.Builder()
.requireLensFacing(CameraSelector.LENS_FACING_BACK)
.build();
// Connect the preview use case to the previewView
preview.setSurfaceProvider(
previewView.createSurfaceProvider());
// Set up the capture use case to allow users to take photos
ImageCapture imageCapture = new ImageCapture.Builder()
.setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY)
.build();
ImageAnalysis imageAnalysis =
new ImageAnalysis.Builder()
.build();
imageAnalysis.setAnalyzer(executor, new ImageAnalysis.Analyzer() {
#Override
public void analyze(#NonNull ImageProxy image) {
int rotationDegrees = image.getImageInfo().getRotationDegrees();
Log.i("CameraXApp3", "Image Analyzed");
image.close();
}
});
// Attach use cases to the camera with the same lifecycle owner
// ------ Code Crashes Here --------------
Camera camera = cameraProvider.bindToLifecycle(
((LifecycleOwner) this),
cameraSelector,
preview,
imageCapture);
} catch (InterruptedException | ExecutionException e) {
// Currently no exceptions thrown. cameraProviderFuture.get() should
// not block since the listener is being called, so no need to
// handle InterruptedException.
}
}, ContextCompat.getMainExecutor(this));
}
}
Full logcat surrounding the IllegalArgumentException
2020-07-29 13:31:57.954 7345-7345/? E/Finsky: [2] VerifyPerSourceInstallationConsentInstallTask.b(2): Package name null is not an installed package
2020-07-29 13:31:59.660 462-877/? E/cutils: Failed to open(/data/misc/profiles/cur/0/jp.oist.cameraxapp/primary.prof): No such file or directory
2020-07-29 13:31:59.660 462-877/? E/installed: Failed to prepare /data/misc/profiles/cur/0/jp.oist.cameraxapp/primary.prof: No such file or directory
2020-07-29 13:31:59.661 729-756/? E/ArtManagerService: Failed to prepare profile for jp.oist.cameraxapp:/data/app/jp.oist.cameraxapp-HSYslGAf7kOyD4tEcVKEkw==/base.apk
2020-07-29 13:32:00.305 462-877/? E/installd: Failed to delete /data/app/vmdl841803495.tmp: No such file or directory
2020-07-29 13:32:00.846 729-729/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/lib/arm, /data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/base.apk!/lib/armeabi-v7a, /system/lib, /system/vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:338)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5441)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1740)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:500)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:839)
2020-07-29 13:32:00.847 729-729/? E/LoadedApk: Unable to instantiate appComponentFactory
java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.CoreComponentFactory" on path: DexPathList[[],nativeLibraryDirectories=[/data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/lib/arm, /data/app/sk.baka.aedict3-FT98hpKmmu7AEcH7jl4_Lw==/base.apk!/lib/armeabi-v7a, /system/lib, /system/vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at android.app.LoadedApk.createAppFactory(LoadedApk.java:226)
at android.app.LoadedApk.updateApplicationInfo(LoadedApk.java:338)
at android.app.ActivityThread.handleDispatchPackageBroadcast(ActivityThread.java:5441)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1740)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at com.android.server.SystemServer.run(SystemServer.java:500)
at com.android.server.SystemServer.main(SystemServer.java:322)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:839)
2020-07-29 13:32:02.251 11105-11105/jp.oist.cameraxapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: jp.oist.cameraxapp, PID: 11105
java.lang.IllegalArgumentException: No available camera can be found.
at androidx.camera.core.CameraSelector.filter(CameraSelector.java:100)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:389)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:275)
at jp.oist.cameraxapp.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:80)
at jp.oist.cameraxapp.-$$Lambda$MainActivity$N0aObN0KVyRMowRsss_pmN8BZ44.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6698)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
2020-07-29 13:32:02.367 2459-9800/ch.deletescape.lawnchair.ci E/pe.lawnchair.c: Failed to open APK '/data/app/jp.oist.cameraxapp-bhz9WJnVll-cJYJKM51yGg==/base.apk' I/O error
2020-07-29 13:32:02.368 2459-9800/ch.deletescape.lawnchair.ci E/ResourcesManager: failed to add asset path /data/app/jp.oist.cameraxapp-bhz9WJnVll-cJYJKM51yGg==/base.apk
Full logcat surrounding the NoSuchElementException
2020-07-29 13:31:22.712 10962-10962/jp.oist.cameraxapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: jp.oist.cameraxapp, PID: 10962
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:759)
at java.util.LinkedHashMap$LinkedKeyIterator.next(LinkedHashMap.java:780)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:415)
at androidx.camera.lifecycle.ProcessCameraProvider.bindToLifecycle(ProcessCameraProvider.java:275)
at jp.oist.cameraxapp.MainActivity.lambda$onCreate$0$MainActivity(MainActivity.java:79)
at jp.oist.cameraxapp.-$$Lambda$MainActivity$N0aObN0KVyRMowRsss_pmN8BZ44.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6698)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
2020-07-29 13:31:22.758 382-382/? E/lowmemorykiller: Error writing /proc/10962/oom_score_adj; errno=22
Edit1:
Tested standard camera app on the Nexus 6 and found that it also crashed. This pointed to a HAL issue presented by a commenter. Restarted the Nexus 6 in an effort to fix the HAL. Now logcat presents a whole new set of errors, but I will save that for a seperate question if I cannot resolve them on my own.
With both LENS_FACING_FRONT and LENS_FACING_BACK resulting in a no available camera can be found, it seems as though no cameras on the device are available for use, this may be caused at times by a HAL crash, and might require a device reboot for the HAL to function correctly again.
You should check the native camera app (or any other camera app for that matter) to see if they are working on the nexus 6 device. If they aren't, then you'll know the issue is in the camera HAL.
My problem is quite a troublesome one, i made an app on Android Studio that has a TextView that displays the Firebase registration token upon launch (I'm still new to Firebase and Android Studio, i'm experimenting), i've been building APK files of my app to test it on my phone since Android Studio doesn't detect my phone when it's hooked to my laptop for some reason and i can't use emulation because my laptop is old (i think it doesn't support virtualization), so whenever i try to launch my app on my phone i get the equivalent of MyApp stopped working in French and i don't know how to view the crash log files.
tl;dr i wanna know what's causing my app to crash
MainActivity.java
package com.gci.gestioncapteursincendie;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
public class MainActivity extends AppCompatActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView= findViewById(R.id.textViewToken);
FirebaseInstanceId.getInstance().getInstanceId()
.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
#Override
public void onComplete(#NonNull Task<InstanceIdResult> task) {
if(task.isSuccessful()){
String token = task.getResult().getToken();
textView.setText("Token : " + token);
}
else
{
textView.setText("Token Not Generated");
}
}
});
}
}
Edit: i managed to run my app on my phone through Android Studio by downloading the right drivers, i checked the logcat when i ran it and i got this:
03-31 18:55:45.069 8855-8855/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gci.gestioncapteursincendie, PID: 8855
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gci.gestioncapteursincendie/com.gci.gestioncapteursincendie.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.gci.gestioncapteursincendie. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.gci.gestioncapteursincendie. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.1:219)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at com.gci.gestioncapteursincendie.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Edit 2:
I added the following line of code referred by user Riley Manda:
FirebaseApp.initializeApp(this);
in onCreate() method and i get this error now:
log trace:
03-31 19:10:19.203 11562-11562/com.gci.gestioncapteursincendie E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gci.gestioncapteursincendie, PID: 11562
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gci.gestioncapteursincendie/com.gci.gestioncapteursincendie.MainActivity}: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.gci.gestioncapteursincendie. Make sure to call FirebaseApp.initializeApp(Context) first.
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Caused by: java.lang.IllegalStateException: Default FirebaseApp is not initialized in this process com.gci.gestioncapteursincendie. Make sure to call FirebaseApp.initializeApp(Context) first.
at com.google.firebase.FirebaseApp.getInstance(com.google.firebase:firebase-common##16.0.1:219)
at com.google.firebase.iid.FirebaseInstanceId.getInstance(Unknown Source)
at com.gci.gestioncapteursincendie.MainActivity.onCreate(MainActivity.java:41)
at android.app.Activity.performCreate(Activity.java:6904)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
at android.app.ActivityThread.access$1100(ActivityThread.java:229)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:7406)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
Edit 3: I'm making another thread about this problem since it seems like the thread has drifted away from its original purpose, thanks everyone for answering.
Connect your app to Crashlytics,this way you will receive crash emails that will lead you to the exact issue thats causing your app to crash.
Follow the instructions on firebase to setup crashlytics for your app in Android Studio.And each time your app crashes, you will receive an email from Crashlytics:
This way, each time your app crashes from your physical devices notification email from Crashlytics is automatically sent to your email indicating the exact line of code/issue that's causing your app to crash.
Based on your crashLog:
You have to initialise firebase in your activity:
Add this to your activity:
FirebaseApp.initializeApp(this);
In your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourlayout);
FirebaseApp.initializeApp(this);
Add this FirebaseApp.initializeApp(this);just after setContentView(R.layout.yourlayout); or before you make any connections to firebase
Also for your device not showing in android studio
first enable developers Options On your Phone https://www.digitaltrends.com/mobile/how-to-get-developer-options-on-android/
Enable Usb Debugging in the developers Options of your Phone settings
Secondly install an adb driver on your System and try reconnecting your device
Accept the prompt on your phone that asks if you want to trust your system and it should work
If I try to use the following code, I am able to use Truecaller's SDK and fetch the user's profile if he has truecaller installed.
//has_truecaller = TrueSDK.getInstance().isUsable(); //doesnt work before init() methof
TrueSdkScope trueScope;
TrueSdkScope.Builder sdkBuilder = new TrueSdkScope.Builder(this, sdkCallback)
.consentMode(TrueSdkScope.CONSENT_MODE_POPUP )
.consentTitleOption( TrueSdkScope.SDK_CONSENT_TITLE_VERIFY )
.footerType( TrueSdkScope.FOOTER_TYPE_SKIP );
if(has_truecaller) {
trueScope = sdkBuilder.sdkOptions( TrueSdkScope.SDK_OPTION_WITH_OTP ).build();
}else{
//TODO get mobile number
BaseActivity.USER_MOBILE_NUMBER = "12345677";
trueScope = sdkBuilder.sdkOptions( TrueSdkScope.SDK_OPTION_WITH_OTP ).build();
}
TrueSDK.init(trueScope);
However If i remove Truecaller from the device i get the following error:
2-06 10:38:45.437 25694-25694/com.project.xyz.userclientapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.project.xyz.userclientapp, PID: 25694 java.lang.NoClassDefFoundError:
Failed resolution of: Lretrofit2/converter/gson/GsonConverterFactory;
at com.truecaller.android.sdk.b.c.a(Unknown Source:9)
at com.truecaller.android.sdk.clients.a.<init>(Unknown Source:10)
at com.truecaller.android.sdk.a.<init>(Unknown Source:46)
at com.truecaller.android.sdk.a.a(Unknown Source:2)
at com.truecaller.android.sdk.TrueSDK.init(Unknown Source:5)
at com.project.xyz.userclientapp.login.LoginActivity.setupTrueSdk(LoginActivity.java:49)
at com.project.xyz.userclientapp.login.LoginActivity.onCreate(LoginActivity.java:30)
at android.app.Activity.performCreate(Activity.java:7149)
at android.app.Activity.performCreate(Activity.java:7140)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3017)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
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:1906)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6863)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
You can check if the Truecaller app is present on the device or not by using the following line -
TrueSDK.getInstance().isUsable()
You do need to initialize the SDK using the init() method before checking for this. It will return a boolean true / false depending on wether Truecaller is installed or not.
Also, the logs what you shared are because of missing a library dependency in your android project. Can you try add the following dependency in your gradle. This should help solve the error -
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
I'm trying to retrieve the location of the device calling the method connect of the class LocationClient in my activity, however when the call is made the system crashes with the following exception:
**FATAL EXCEPTION: main
Process: com.unipagossales, PID: 3833
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.unipagossales/com.unipagossales.app.merchants.MerchantFragmentActivity}: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.google.android.location.internal.GoogleLocationManagerService.START }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.google.android.location.internal.GoogleLocationManagerService.START }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1674)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1773)
at android.app.ContextImpl.bindService(ContextImpl.java:1751)
at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
at com.google.android.gms.internal.v.a(Unknown Source)
at com.google.android.gms.internal.u.connect(Unknown Source)
at com.google.android.gms.location.LocationClient.connect(Unknown Source)
at com.unipagossales.app.merchants.MerchantFragmentActivity.onStart(MerchantFragmentActivity.java:122)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1220)
at android.app.Activity.performStart(Activity.java:5949)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2261)
... 10 more
**
This is the way I create my LocationClient:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant_activity);
...
// Create a new global location parameters object
locationRequest = LocationRequest.create();
locationRequest.setInterval(Constants.UPDATE_INTERVAL_MILLISECONDS);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setFastestInterval(Constants.FAST_INTERVAL_CEILING_MILLISECONDS);
// Initialize the location client
locationClient = new LocationClient(this, new LocationClientConnectionCallbacks(), new LocationClientOnConnectionFailedListener());
}
#Override
protected void onStart() {
super.onStart();
...
locationClient.connect();
...
}
Changing the target SDK version to "19" helped me.
This problem is related to the fact that Android VM is not being able in runtime to find the definition of the action act=com.google.android.location.internal.GoogleLocationManagerService.START in Google Play Services.
You will need to set your Google Play Services following the next blog:
http://mflerackers.wordpress.com/2014/09/09/noclassdeffounderror-for-googleplayservicesutil/
Then you will need to increment the VM values in eclipse.ini, follow this one:
Unable to execute dex: GC overhead limit exceeded in Eclipse
This should fix your exception collaterally.
I am using Android Studio. I am using e-POS-Print.jar in my app. Whenever I run the code I get this error:
java.lang.ExceptionInInitializerError
at com.stc.printer.MyActivity.onCreate(MyActivity.java:48)
at android.app.Activity.performCreate(Activity.java:5163)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2061)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2122)
at android.app.ActivityThread.access$600(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1228)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4895)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:994)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:761)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.UnsatisfiedLinkError: Couldn't load eposprint: findLibrary returned null
at java.lang.Runtime.loadLibrary(Runtime.java:365)
at java.lang.System.loadLibrary(System.java:535)
at com.epson.eposprint.Print.<clinit>(Print.java:18)
at com.stc.printer.MyActivity.onCreate(MyActivity.java:48)
My code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
System.out.println("started");
printerName = getString(R.string.printername_t81ii);
language = Builder.MODEL_SOUTHASIA;
//bellow is line no. 48
Print newPrinter = new Print(getApplicationContext());
try{
newPrinter.openPrinter(deviceType, openDeviceName, enabled, interval);
}catch(Exception e){
System.out.println("Error");
e.printStackTrace();
newPrinter = null;
}
setPrinter(newPrinter);
}
The sample project from Epson is having one native file with .so extension. But even if I remove that file from sample project it works.
I also tried adding that file to my project. But I am not able to add that file to my build path.
I also referred multiple answers from this link but I am unsuccessful.
After checking many sites, reading multiple answers, finally I figured out the solution.
Create folder tree as:
|---src
|---main
|---jniLibs
|---armeabi
|---nativeLib.so
Place your files under armeabi folder. And it will work.
More about java.lang.unsatisfiedlinkerror