Fatal Exception OkHttp Dispatcher with RetroFit - java

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

Related

Imported Gradle Dependency not working at Java runtime

We are migrating to using the Microsoft Graph API from using older auth methods.
Previously in this project the dependency management has been very manual, this included downloading .jars and manually importing them into intelliJ for local development.
Since we need to pull in new dependencies for the Graph API SDK, I took it as a chance to pay off some tech-debt and start going toward more programmatic dependency management.
I was able to get the web-app to run properly, however bringing in the new dependencies
https://mvnrepository.com/artifact/com.microsoft.azure/msal4j
https://mvnrepository.com/artifact/com.microsoft.graph/microsoft-graph
https://mvnrepository.com/artifact/com.azure/azure-core
did not seem to work fully.
Our build.gradle looks like this
dependencies {
providedCompile 'com.microsoft.graph:microsoft-graph:5.40.0'
providedCompile 'com.azure:azure-identity:1.7.0'
// https://mvnrepository.com/artifact/com.azure/azure-core
implementation group: 'com.azure', name: 'azure-core', version: '1.34.0'
// https://mvnrepository.com/artifact/com.microsoft.azure/msal4j
implementation 'com.microsoft.azure:msal4j:1.13.3'
providedCompile fileTree(dir: "${webAppDirName}/WEB-INF/lib", excludes: [
'aspose.pdf.jar',
'aspose-pdf.jar',
'async-http-client-2.4.4.jar',
'commons-beanutils-core.jar',
'commons-collections.jar',
'commons-fileupload-1.1.jar',
'commons-fileupload-1.2.2.jar',
'commons-io-1.1.jar',
'commons-io-2.1.jar',
'commons-lang-2.3.jar',
'commons-logging.jar',
'commons-logging-1.0.jar',
'commons-logging-1.1.1.jar',
'commons-logging-1.1.3.jar',
'core-1.5.0.jar',
'empty.jar',
'firebase-admin-6.3.0.jar',
'groovy-all-1.7.5.jar',
'httpclient-4.1.2.jar',
'httpclient-4.5.jar',
'httpcore-4.1.2.jar',
'httpcore-4.4.1.jar',
'httpmime-4.1.2.jar',
'itext-2.0.4.jar',
'jackson-annotations-2.4.0.jar',
'jackson-annotations-2.8.0.jar',
'jackson-core-2.4.0.jar',
'jackson-databind-2.4.0-rc3.jar',
'jackson-jaxrs-1.9.2.jar',
'jackson-xc-1.9.2.jar',
'jasperreports-5.6.0.jar',
'jersey-json-1.17.1.jar',
'jsch-0.1.53.jar',
'json_simple-1.1.jar',
'mailapi.jar',
'netty-all-4.1.23.Final.jar',
'opentok-server-sdk-2.2.0.jar',
'opentok-server-sdk-4.2.0.jar',
'reactive-streams-1.0.2.jar',
'servlet.jar',
'soap.jar',
'twilio-7.1.0-jar-with-dependencies.jar',
'twilio-java-sdk-3.3.10-jar-with-dependencies.jar',
'webprovider-1.5.0.jar'
],include:'*.jar')
providedCompile 'org.apache.tomcat:tomcat-catalina:8.5.32'
}
The code in particular that I am running into an issue with is located here
public MicrosoftEmailClient() {
ClientSecretCredential clientSecretCredential = new ClientSecretCredentialBuilder()
.clientId(CLIENT_ID)
.clientSecret(CLIENT_SECRET)
.tenantId(TENANT_ID)
.build();
TokenCredentialAuthProvider tokenCredentialAuthProvider = new TokenCredentialAuthProvider(SCOPE, clientSecretCredential);
graphClient =
GraphServiceClient
.builder()
.authenticationProvider(tokenCredentialAuthProvider)
.buildClient();
}
and the error itself is here
Exception in thread "Thread-8" java.lang.NoClassDefFoundError: com/azure/core/credential/TokenCredential
For context around this project we are deploying it through Tomcat 8.5+

core-ktx 1.7.0 and Hilt

I've just updated my project's core-ktx (androidx.core:core-ktx) version to 1.7.0, and now I can't compile my project. In fact, at my PC everything works OK, but in Github Actions the build is broken.
At first I was getting this error:
* What went wrong:
Execution failed for task ':core:verifyReleaseResources'.
> A failure occurred while executing com.android.build.gradle.tasks.VerifyLibraryResourcesTask$Action
> Android resource linking failed
ERROR:/home/runner/.gradle/caches/transforms-3/cf34be3e77386540a828d329143911c7/transformed/core-1.7.0/res/values/values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.
But updating to SDK 31 fixed this issue. Now I'm getting the following one:
> Task :core:hiltAggregateDepsDebugUnitTest
WARNING: [Processor] Library '/home/runner/.gradle/caches/transforms-3/fd6df19df5b3c35086ae117610be6db2/transformed/browser-1.0.0-api.jar' contains references to both AndroidX and old support library. This seems like the library is partially migrated. Jetifier will try to rewrite the library anyway.
Example of androidX reference: 'androidx/browser/R$styleable'
Example of support library reference: 'android/support/customtabs/ICustomTabsCallback$Stub$Proxy'
WARNING: [Processor] Library '/home/runner/.gradle/caches/transforms-3/fc7ccfb37357e9edd2e98ab346848a40/transformed/core-1.7.0-api.jar' contains references to both AndroidX and old support library. This seems like the library is partially migrated. Jetifier will try to rewrite the library anyway.
Example of androidX reference: 'androidx/core/R$styleable'
Example of support library reference: 'android/support/v4/app/INotificationSideChannel$Default'
> Task :core:javaPreCompileReleaseUnitTest
> Task :core:compileReleaseUnitTestJavaWithJavac NO-SOURCE
> Task :core:createFullJarRelease
/home/runner/work/Android/Android/core/build/generated/hilt/component_sources/debugUnitTest/com/***/.../core/shared/Hilt_App.java:20: error: cannot find symbol
return DaggerApp_HiltComponents_SingletonC.builder()
> Task :core:hiltJavaCompileDebugUnitTest FAILED
^
symbol: variable DaggerApp_HiltComponents_SingletonC
1 error
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':core:hiltJavaCompileDebugUnitTest'.
> Compilation failed; see the compiler error output for details.
This is my build.gradle:
plugins {
id 'com.android.library'
id 'kotlin-android'
id 'kotlin-parcelize'
id 'org.jetbrains.dokka'
id 'org.jetbrains.kotlin.kapt'
id 'dagger.hilt.android.plugin'
}
android {
compileSdk 31
buildToolsVersion "31.0.0"
defaultConfig {
minSdk 24
targetSdk 31
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
vectorDrawables {
useSupportLibrary true
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
buildFeatures {
viewBinding true
compose true
}
composeOptions {
kotlinCompilerExtensionVersion compose_version
}
}
tasks.named("dokkaHtmlPartial") {
dokkaSourceSets {
configureEach {
noAndroidSdkLink.set(false)
}
}
}
dependencies {
implementation 'org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.5.31'
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.preference:preference-ktx:1.1.1'
// Testing
testImplementation 'junit:junit:4.13.2'
testImplementation 'org.mockito:mockito-core:4.0.0'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
// KotlinX Coroutines
api 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2'
api 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2'
api 'org.jetbrains.kotlinx:kotlinx-coroutines-play-services:1.5.2'
// Android Jetpack
def jetpack_work_version = '2.7.0'
api "androidx.work:work-runtime-ktx:$jetpack_work_version"
api "androidx.work:work-gcm:$jetpack_work_version"
androidTestApi "androidx.work:work-testing:$jetpack_work_version"
api "androidx.startup:startup-runtime:1.1.0"
// Jetpack compose
api "androidx.compose.ui:ui:$compose_version"
api "androidx.compose.ui:ui-tooling:$compose_version"
api "androidx.compose.foundation:foundation:$compose_version"
api "androidx.compose.material:material:$compose_version"
api "androidx.compose.material:material-icons-core:$compose_version"
api "androidx.compose.material:material-icons-extended:$compose_version"
api "androidx.compose.runtime:runtime-livedata:$compose_version"
api "androidx.compose.runtime:runtime-rxjava2:$compose_version"
api 'androidx.activity:activity-compose:1.4.0'
api 'androidx.lifecycle:lifecycle-viewmodel-compose:2.4.0'
api 'androidx.navigation:navigation-compose:2.4.0-beta02'
api 'com.google.accompanist:accompanist-appcompat-theme:0.20.1'
androidTestApi "androidx.compose.ui:ui-test-junit4:$compose_version"
// Coil image loading
api 'io.coil-kt:coil:1.4.0'
api 'io.coil-kt:coil-compose:1.4.0'
// Live Data
api 'androidx.lifecycle:lifecycle-livedata-ktx:2.4.0'
// Google Play Core
api 'com.google.android.play:core:1.10.2'
api 'com.google.android.play:core-ktx:1.8.1'
// App Search
def appsearch_version = "1.0.0-alpha04"
api "androidx.appsearch:appsearch:$appsearch_version"
// Use kapt instead of annotationProcessor if writing Kotlin classes
kapt "androidx.appsearch:appsearch-compiler:$appsearch_version"
api "androidx.appsearch:appsearch-local-storage:$appsearch_version"
// Google Firebase
api platform('com.google.firebase:firebase-bom:29.0.0')
api 'com.google.firebase:firebase-analytics-ktx'
api 'com.google.firebase:firebase-firestore-ktx'
api 'com.google.firebase:firebase-storage-ktx'
api 'com.google.firebase:firebase-crashlytics-ktx'
api 'com.google.firebase:firebase-config-ktx'
api 'com.google.firebase:firebase-perf-ktx'
api 'com.google.firebase:firebase-dynamic-links-ktx'
api 'com.google.firebase:firebase-functions-ktx'
api 'com.google.firebase:firebase-auth-ktx'
api 'com.google.firebase:firebase-messaging-ktx'
api 'com.google.firebase:firebase-messaging-directboot:23.0.0'
// Google Firebase Auth Google Sign-In
api 'com.google.android.gms:play-services-auth:19.2.0'
// Hilt dependency injection
api "com.google.dagger:hilt-android:2.40"
kapt "com.google.dagger:hilt-compiler:2.40"
// Gson for JSON parsing
implementation 'com.google.code.gson:gson:2.8.9'
// Maps SDK
api 'com.google.android.gms:play-services-maps:18.0.0'
// Timber
api 'com.jakewharton.timber:timber:5.0.1'
// Custom Views
api 'com.github.PhilJay:MPAndroidChart:v3.1.0'
}
If any extra info is required please ask, my build workflow has been broken for a week :(
Thanks in advance
Implement a new version of androidx.core-ktx in your project .
implementation 'androidx.core:core-ktx:1.8.0-alpha03'
then force the project to use the new version of it.
configurations.all {
resolutionStrategy { force 'androidx.core:core-ktx:1.8.0-alpha03' }
}
just only remove line
implementation 'androidx.core:core-ktx:1.7.0'
that should fix the warning

log4j2 with Mongodb issue logging throwable with message

I'm trying to setup log4j2 with mongoDb3 and everything works fine, only problem is when I long throwable exception with message something like this
logger.error("Some Message",new Exception("Test"));
I will get an error as
Caused by: org.bson.codecs.configuration.CodecConfigurationException: Can't find a codec for class org.apache.logging.log4j.mongodb3.MongoDbDocumentObject.
but I can easily log error with
logger.error(new Exception("Test"));
without any issue.
Our project is using slf4j mainly for logging and all of our error logs styled like the first example.
is there any way I can fix this error without changing all the exception logs?
Also my config is fairly simple
<NoSql name="databaseAppender">
<MongoDb3 databaseName="admin" collectionName="testLogger" server="localhost"
username="***" password="****" />
</NoSql>
Thank you
After lot's of headache and testing I figured out how to solve this problem.
I just post my result here incase someone else ran into this issue.
For some reason org.apache.logging.log4j.mongodb3.MongoDbDocumentObject is not getting register by MongoDb codecs automatically so I have to create a ConnectionFactory class to register the class .
public static MongoClient getMongoClient () {
MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder()
.codecRegistry(CodecRegistries.fromRegistries(
CodecRegistries.fromCodecs(new LevelCodec()),
CodecRegistries.fromProviders(PojoCodecProvider.builder().register(MongoDbDocumentObject.class).build()),
MongoClient.getDefaultCodecRegistry()));
MongoClientURI uri = new MongoClientURI("mongodb://"+userName+":"+passWord+"#"+dbUrl+":"+port,optionsBuilder);
return new MongoClient(uri);
}
Obviously you have to change your log4j Appender to use the class and method :
<NoSql name="databaseAppender">
<MongoDb3 databaseName="test" collectionName="testLogger" factoryClassName="ClassName"
factoryMethodName="getMongoClient" />
</NoSql>
My dependancies are :
implementation group: 'org.slf4j', name: 'slf4j-api', version: '1.7.30'
// Log4j
implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.13.3'
implementation group: 'org.apache.logging.log4j', name:'log4j-mongodb3', version:'2.13.3'
implementation group: 'org.apache.logging.log4j', name: 'log4j-slf4j-impl', version: '2.13.3'
implementation group:'com.fasterxml.jackson.dataformat',name:'jackson-dataformat-xml', version:'2.9.4'
// https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver
implementation group: 'org.mongodb', name: 'mongo-java-driver', version: '3.12.7'

How to authenticate Android app to connect with Spotify?

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.

ServiceConfigurationError thrown when trying to create new Jetty WebSocketClient instance

I am trying to create a new WebSocketClient with no args constructor for cometD:
static BayeuxClient newInstace(String url) throws Exception {
WebSocketClient wsClient = new WebSocketClient(); //exception here!!
wsClient.start();
Map<String, Object> options = new HashMap<>();
ClientTransport transport = new JettyWebSocketTransport(options, Executors.newScheduledThreadPool(2), wsClient);
BayeuxClient client = new BayeuxClient(url, transport);
return client;
}
But this is throwing runtime exception:
java.util.ServiceConfigurationError: org.eclipse.jetty.websocket.api.extensions.Extension: Provider org.eclipse.jetty.websocket.common.extensions.identity.IdentityExtension not found
at java.util.ServiceLoader.fail(ServiceLoader.java:225)
at java.util.ServiceLoader.-wrap1(ServiceLoader.java)
at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:366)
at java.util.ServiceLoader$1.next(ServiceLoader.java:448)
at org.eclipse.jetty.websocket.api.extensions.ExtensionFactory.<init>(ExtensionFactory.java:35)
at org.eclipse.jetty.websocket.client.common.extensions.WebSocketExtensionFactory.<init>(WebSocketExtensionFactory.java:36)
at org.eclipse.jetty.websocket.client.WebSocketClient.<init>(WebSocketClient.java:117)
at org.eclipse.jetty.websocket.client.WebSocketClient.<init>(WebSocketClient.java:108)
at org.eclipse.jetty.websocket.client.WebSocketClient.<init>(WebSocketClient.java:88)
at org.asd.util.customerSupportChat.LekaneClient.newInstace(LekaneClient.java:40)
This is happening on Android
minSdkVersion 21
targetSdkVersion 25
And I have included the library like this:
//https://mvnrepository.com/artifact/org.cometd.java/cometd-java-websocket-jetty-client/3.1.2
compile group: 'org.cometd.java', name: 'cometd-java-websocket-jetty-client', version: '3.1.2'
Do you know what is wrong and how can I fix this?
--------------- edit ----------------
this was also in the stacktrace:
Caused by: java.lang.ClassNotFoundException: Didn't find class "org.eclipse.jetty.websocket.common.extensions.identity.IdentityExtension" on path: DexPathList[[zip file "/data/app/org.asd.debug-2/base.apk"],nativeLibraryDirectories=[/data/app/org.asd.debug-2/lib/x86, /system/lib, /vendor/lib]]
As sbordet mentioned in the comments, the problem was with missing dependencies. Adding this to build.gradle fixed the problem:
compile group: 'org.eclipse.jetty.websocket', name: 'websocket-common', version: '9.2.22.v20170606'
(using old version because don't have Java 8 available)
Don't know why it isn't resolved automatically though.

Categories

Resources