How to authenticate Android app to connect with Spotify? - java

I want to create my own (non-commercial) DDR app on my phone for fun that uses music from Spotify.
So far I've tried to follow the quickstart tutorial: https://developer.spotify.com/documentation/android/quick-start/
I have created a template app, with just a hello world screen in android studio.
I have the spotify app installed, and I'm logged in with a premium account.
I went to the spotify developer dashboard and registered my app. My app is called MyDDR for now.
I have the redirect URI set to 192.168.1.23:5000/callback, a flask server running on my PC. I tested it, and my phone can connect to it. I don't know if this is relevant since there is no traffic triggered by my code for now.
Then I added my fingerprint and package name to the app I registered in the spotify developer dashboard. Here are my results from that:
I created a signed bundle, with a keystore created following this tutorial.
I only did the 'register app fingerprints' part, since the page seemed to be just an old version of the quickstart guide I was already following.
Running the gradle task signingReport revealed the same SHA1 key that was in my keystore by checking it manually.
> Task :app:signingReport
Variant: release
Config: none
----------
Variant: debug
Config: debug
Store: C:\Users\[name]\.android\debug.keystore
Alias: AndroidDebugKey
MD5: [removed]
SHA1: [mysha1key]
SHA-256: [removed]
Valid until: Wednesday, 8 September 2049
----------
[3 other variants, debugUnitTest, debugAndroidTest, releaseUnitTest]
I'm not familiar with signing apps, so I'm not sure it did it right.
As far as I understand it I only need to concern myself with debug right? I don't have plans releasing this to the play store.
Here is my android studio setup:
As you can see my package name is com.example.myddr
And finally I added my package name and fingerprint in the spotify developer dashboard:
I had downloaded the Spotify Android SDK, by downloading the spotify-app-remote-release-0.6.3.aar file and adding it as a new module. I added the module/project to my build.gradle (Module: app) dependencies, together with gson, like the tutorial instructed.
dependencies {
implementation project(':spotify-app-remote')
implementation "com.google.code.gson:gson:2.8.5"
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Now I was ready for the step 'Authorizing the user using the built-in auth flow'
This is the code so far
package com.example.myddr;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
import com.spotify.android.appremote.api.ConnectionParams;
import com.spotify.android.appremote.api.Connector;
import com.spotify.android.appremote.api.SpotifyAppRemote;
import com.spotify.protocol.client.Subscription;
import com.spotify.protocol.types.PlayerState;
import com.spotify.protocol.types.Track;
public class MainActivity extends AppCompatActivity {
private static final String CLIENT_ID = "2d6a5307b3024e7b9b32d52146150986";
private static final String REDIRECT_URI = "http://192.168.1.23:5000/callback";
private SpotifyAppRemote mSpotifyAppRemote;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
ConnectionParams connectionParams =
new ConnectionParams.Builder(CLIENT_ID)
.setRedirectUri(REDIRECT_URI)
.showAuthView(true)
.build();
SpotifyAppRemote.connect(this, connectionParams,
new Connector.ConnectionListener() {
public void onConnected(SpotifyAppRemote spotifyAppRemote) {
mSpotifyAppRemote = spotifyAppRemote;
Log.d("MainActivity", "Connected! Yay!");
// Now you can start interacting with App Remote
connected();
}
public void onFailure(Throwable throwable) {
Log.e("MainActivity", throwable.getMessage(), throwable);
// Something went wrong when attempting to connect! Handle errors here
}
});
}
private void connected() {
}
}
However when running this I get a lot of warnings like this:
W/m.example.mydd: Unable to resolve Lcom/spotify/protocol/types/HelloDetails; annotation class 28
W/m.example.mydd: Unable to resolve Lcom/spotify/protocol/types/HelloDetails; annotation class 31
W/m.example.mydd: Unable to resolve Lcom/spotify/protocol/types/Info; annotation class 28
W/m.example.mydd: Unable to resolve Lcom/spotify/protocol/types/Info; annotation class 31
And finally an error:
E/MainActivity: {"message":"com.spotify.mobile.android.spotlets.appprotocol.model.AppProtocol$Message"}
com.spotify.android.appremote.api.error.AuthenticationFailedException: {"message":"com.spotify.mobile.android.spotlets.appprotocol.model.AppProtocol$Message"}
at com.spotify.android.appremote.api.LocalConnector.asAppRemoteException(LocalConnector.java:131)
at com.spotify.android.appremote.api.LocalConnector.access$000(LocalConnector.java:35)
at com.spotify.android.appremote.api.LocalConnector$1.onConnectionFailed(LocalConnector.java:111)
at com.spotify.android.appremote.internal.SdkRemoteClientConnector$ConnectionTask.onPostExecute(SdkRemoteClientConnector.java:142)
at com.spotify.android.appremote.internal.SdkRemoteClientConnector$ConnectionTask.onPostExecute(SdkRemoteClientConnector.java:75)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.access$600(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6898)
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)
Caused by: com.spotify.protocol.client.error.RemoteClientException: {"message":"com.spotify.mobile.android.spotlets.appprotocol.model.AppProtocol$Message"}
at com.spotify.protocol.client.RemoteWampClient.getRemoteClientException(RemoteWampClient.java:139)
at com.spotify.protocol.client.RemoteWampClient.access$200(RemoteWampClient.java:16)
at com.spotify.protocol.client.RemoteWampClient$1.onAbort(RemoteWampClient.java:44)
at com.spotify.protocol.client.WampRouterImpl.routeAbort(WampRouterImpl.java:100)
at com.spotify.protocol.client.WampRouterImpl.route(WampRouterImpl.java:26)
at com.spotify.protocol.client.AppProtocolCommunicator.onData(AppProtocolCommunicator.java:78)
at com.spotify.android.appremote.internal.RemoteServiceIo.handleMessage(RemoteServiceIo.java:113)
at com.spotify.android.appremote.internal.RemoteServiceIo.access$000(RemoteServiceIo.java:47)
at com.spotify.android.appremote.internal.RemoteServiceIo$IncomingHandler.handleMessage(RemoteServiceIo.java:91)
at android.os.Handler.dispatchMessage(Handler.java:106) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:6898) 
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) 
This error means that I couldn't connect to Spotify due to an AuthenticationFailedException. Googling the error delivered no satisfying solutions. I only found people who had forgotten to register their fingerprint, but as far as I know I've done that. But I'm also suspicious that I did not do it correctly, because it seems fairly complicated.

Related

Illegal ArgumentException: "No available camera can be found" in CameraProcessProvider.bindToLifecycle for Nexus 6

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.

How to fix Android app crashing that uses Firebase?

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

Fatal Exception OkHttp Dispatcher with RetroFit

I am using RetroFit to make a call to TheMovieDatabase API and am trying to get a list of the popular movies to populate into a RecylerView. However, when I make the call through RetroFit, I am getting an error related to OkHTTP. I am using OkHTTP in conjunction with RetroFit:
06-08 19:57:26.281 19232-19254/popularmovies.troychuinard.com.popularmovies E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
Process: popularmovies.troychuinard.com.popularmovies, PID: 19232
java.lang.NoClassDefFoundError: Failed resolution of: Lokhttp3/internal/Platform;
at okhttp3.logging.HttpLoggingInterceptor$Logger$1.log(HttpLoggingInterceptor.java:112)
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:160)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
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 "okhttp3.internal.Platform" on path: DexPathList[[zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/base.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_dependencies_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_0_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_1_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_2_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_3_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_4_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_5_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_6_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_7_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_8_apk.apk", zip file "/data/app/popularmovies.troychuinard.com.popularmovies-2/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/popularmovies.troychuinard.com.popularmovies-2/lib/arm, /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 okhttp3.logging.HttpLoggingInterceptor$Logger$1.log(HttpLoggingInterceptor.java:112) 
at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.java:160) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147) 
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121) 
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200) 
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:147) 
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32) 
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) 
Below is my relevant code from RetroFit:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), String.valueOf(i), Toast.LENGTH_LONG).show();
String selection = String.valueOf(i);
switch (i){
case 0:
query = "popular";
mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
break;
case 1:
query = "top_rated";
mBaseURL = "https://api.themoviedb.org/3/movie/top_rated/";
break;
default:
query = "popular";
mBaseURL = "https://api.themoviedb.org/3/movie/popular/";
break;
}
mMovieURLS.clear();
mMovieResultsAdapter.notifyDataSetChanged();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient
.Builder()
.addInterceptor(interceptor)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(mBaseURL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
Call<TheMovieDatabase> call = apiInterface.getImages();
call.enqueue(new Callback<TheMovieDatabase>() {
#Override
public void onResponse(Call<TheMovieDatabase> call, Response<TheMovieDatabase> response) {
String movieResponse = String.valueOf(response.isSuccessful());
Log.v("SUCESS", movieResponse);
}
#Override
public void onFailure(Call<TheMovieDatabase> call, Throwable t) {
}
});
}
API InterFace:
public interface ApiInterface{
#GET("?api_key=xxxxxxxxx&language=en-US")
Call<TheMovieDatabase> getImages();
}
Gradle Dependencies:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.3.0'
}
I know this question has been 2 years, but I solve mine. So here is an alternate answer you could try.
My error started after upgrading version of my dependencies(Android Studio suggested it after looking in project structure). Since the problem involve Retrofit and OkHttp, I revert back to the older version that I use, when my app was working. So, I suggest to revert back to older version of :
implementation 'com.squareup.retrofit2:retrofit:*older version here*'
implementation 'com.squareup.retrofit2:converter-gson:*older version here*'
implementation 'com.squareup.retrofit2:converter-moshi:*older version here*'
implementation 'oauth.signpost:oauth-signpost:*older version here*'
implementation 'se.akerfeldt:okhttp-signpost:*older version here*'
implementation 'com.squareup.okhttp3:okhttp:*older version here*'
implementation 'oauth.signpost:signpost-core:*older version here*'
That is the dependencies that I revert back to older version. I suggest you change any Retrofit or OkHttp related dependencies back to older version when your app was working.
If you have any problem figuring out what is the older version that is available, I suggest to look into dependencies version from Project Structure > Dependencies tab > app tab. from there you can find your dependencies that you are looking for, and change the version.
Good luck

Android Studio: connecting to MongoDB server with Mongo Java Driver

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.

Android - java.lang.VerifyError on SDK 2.2

I recently launched my application to the Market and I've been in contact with a user who is reporting that when he launches my app, it display the Force Close/Report dialog. I asked the user to report the error so I could see the stack trace of what's happening and I'm getting the java.lang.VerifyError.
From what I've read, this has either something to do with an external library or an incompatibility in some method in java.lang with the targeted Android SDK version.
The user is on Android 2.2.1, but the app currently works on many other 2.2 devices, so I'm trying to figure out where to start digging.
Question:
Does anybody have suggestions as to what would be the best thing to start looking into to find the issue? I can provide code or more information if needed, so please let me know.
Here's the Stack Trace:
java.lang.VerifyError: com.app.myapp.MainActivity
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1429)
at android.app.Instrumentation.newActivity(Instrumentation.java:1034)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2749)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2866)
at android.app.ActivityThread.access$2300(ActivityThread.java:140)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2181)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:143)
at android.app.ActivityThread.main(ActivityThread.java:5097)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:521)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
at dalvik.system.NativeStart.main(Native Method)
Thanks in advance!
EDIT
Added per request of Konstantin
MainActivity.java
package com.app.myapp;
//Imports removed
public class MainActivity extends BaseActivity implements Runnable {
private LayoutInflater mInflater;
private SharedPreferences prefs;
private SharedPreferences.Editor prefsEditor;
....
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
loadActivity(savedInstanceState);
}
private void loadActivity(Bundle savedInstanceState) {
setContentView(R.layout.mainlayout);
ActionBar actionBar = (ActionBar)findViewById(R.id.actionbar);
actionBar.setTitle("My App");
actionBar.setHomeAction(new IntentAction(this, null, R.drawable.ic_actionbar_home));
actionBar.addAction(new SearchAction(this, R.drawable.ic_actionbar_search));
weatherThread = new Thread(this);
try {
....Unrelated Code....
//****HERE WAS THE PROBLEM****//
Gson gson = new Gson();
....More Unrelated Code....
} catch (JsonSyntaxException ex) { }
initMembers();
initControls();
if (savedInstanceState != null) {
mSelectedLayout = savedInstanceState.getInt("CURRENT_TAB");
setCurrentTab();
}
else
loadMainLayout();
}
....Other unrelated code....
}
There are a few devices which are using GSON internally, but made the library public, causing a namespace conflict when the application attempts to reference its packaged version of gson. A possible workaround is changing the namespace of the gson jar you have included using jarjar.
Heres a thread on the issue - The thread contains a description of at least one workaround supplied by another developer who encountered the same issue.
there could be mismatch with the libs like Gson you have compiled and libs which are used in run time.
Ref - Causes of getting a java.lang.VerifyError
It looks like ActionBar was released since API level 11 only, while android 2.2 is somewhat older (API level 8). So try it without the action bar. I do not know if the view was backported to 2.2 platform, but even if it was, your user can still have old 2.2 version..
Check that you are compiling against the correct Android SDK version. What is minSDK in your AndroidManifest.xml?

Categories

Resources