While trying to use GET request in my project, I stumbled a problem: I can't import java.net.http.
Here's part of my code (just an example, that I'm trying to reproduce):
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
fun String.utf8(): String = URLEncoder.encode(this, "UTF-8")
fun main() {
val params = mapOf("name" to "John Doe", "occupation" to "gardener")
val urlParams = params.map {(k, v) -> "${(k.utf8())}=${v.utf8()}"}
.joinToString("&")
val client = HttpClient.newBuilder().build();
val request = HttpRequest.newBuilder()
.uri(URI.create("https://httpbin.org/get?${urlParams}"))
.build();
val response = client.send(request, HttpResponse.BodyHandlers.ofString());
println(response.body())
}
Build output:
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (16, 17): Unresolved reference: http
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (17, 17): Unresolved reference: http
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (18, 17): Unresolved reference: http
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (29, 18): Unresolved reference: HttpClient
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (30, 19): Unresolved reference: HttpRequest
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (34, 41): Unresolved reference: HttpResponse
e: C:\Users\BJayD\AndroidStudioProjects\Viva_La_Resistance_Radio\VLR-Radio\app\src\main\java\com\example\viva_la_resistance_radio\Info.kt: (129, 23): Unresolved reference: HttpRequest
Here's my buld.gradle, since I found that the problem is usually with incompatibility between Java 8 and 11:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.0'
}
}
plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
}
android {
namespace 'com.example.viva_la_resistance_radio'
compileSdk 33
defaultConfig {
applicationId "com.example.viva_la_resistance_radio"
minSdk 21
targetSdk 33
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_11
targetCompatibility JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = '11'
}
}
dependencies {
implementation 'androidx.core:core-ktx:1.9.0'
implementation 'androidx.appcompat:appcompat:1.6.0'
implementation 'com.google.android.material:material:1.8.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}
I updated Java already, changed settings, but nothing helps.
I think I've made a mistake somewhere else, but can't find anything.
The classes you are trying to use are not part of the Android platform. These are Java SE classes that were introduced in Java 11.
Unless the answers to How can I use JDK 11 HTTP packages in Android are out of date, there are no ports of the java.net.http.* classes to Android (yet).
I recommend that you use one of the 3rd-party libraries listed in Make an HTTP request with android. The respective documentation will include examples for you to follow ... if that is what you need.
Related
I'm developing an application that allows the user to contact me by sending an email (the user only inputs the message, sender and receiver emails are both mine). I'm trying to implement this with gmail using the JavaMail API. However, I keep getting this error at the Transport.send(mimeMessage) line.
Here are the error messages:
Caused by: java.lang.VerifyError: Rejecting class com.sun.mail.handlers.text_plain that attempts to sub-type erroneous class com.sun.mail.handlers.handler_base (declaration of 'com.sun.mail.handlers.text_plain' appears in /data/app/~~T_TRkO9R_v9j4iEdr4K9Yg==/com.example.compusec-dPeAL8DtGJvU45dJpt8xxA==/base.apk)
Caused by: java.lang.VerifyError: Verifier rejected class com.sun.mail.handlers.handler_base: java.awt.datatransfer.DataFlavor[] com.sun.mail.handlers.handler_base.getTransferDataFlavors() failed to verify: java.awt.datatransfer.DataFlavor[] com.sun.mail.handlers.handler_base.getTransferDataFlavors(): [0x4] can't resolve returned type 'Unresolved Reference: java.awt.datatransfer.DataFlavor[]' or 'Reference: javax.activation.ActivationDataFlavor[]' (declaration of 'com.sun.mail.handlers.handler_base' appears in /data/app/~~T_TRkO9R_v9j4iEdr4K9Yg==/com.example.compusec-dPeAL8DtGJvU45dJpt8xxA==/base.apk)
Here is my code:
protected Void doInBackground(Void... voids) {
Properties properties = new Properties();
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.socketFactory.port", "465");
properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.port", "465");
session = javax.mail.Session.getInstance(properties, new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("sender#gmail.com","senderpass");
}
});
session.setDebug(true);
MimeMessage mimeMessage = new MimeMessage(session);
try {
mimeMessage.setFrom(new InternetAddress("sender#gmail.com"));
mimeMessage.addRecipients(Message.RecipientType.TO, String.valueOf(new InternetAddress(email)));
mimeMessage.setSubject(subject);
mimeMessage.setText(message);
Transport.send(mimeMessage);
} catch (MessagingException e) {
e.printStackTrace();
}
return null;
}
And the gradle script:
plugins {
id 'com.android.application'
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.2"
packagingOptions {
pickFirst 'META-INF/LICENSE.txt' // picks the JavaMail license file
}
defaultConfig {
applicationId "com.example.myapplication"
minSdkVersion 23
targetSdkVersion 30
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
repositories {
jcenter()
maven {
url "https://maven.java.net/content/groups/public/"
}
}
dependencies {
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
compile 'com.sun.mail:android-mail:1.6.2'
compile 'com.sun.mail:android-activation:1.6.2'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
Use this in build.gradle:
android {
...
packagingOptions {
exclude 'META-INF/NOTICE.md'
exclude 'META-INF/LICENSE.md'
}
}
dependencies {
implementation 'com.sun.mail:android-mail:1.6.6'
implementation 'com.sun.mail:android-activation:1.6.6'
...
}
credit to last few comments on this issue
I am having the same issue. What I can tell you is that if you target Android 10 and lower (SDK 29 or lower) it works fine. I have been using it for years. However, as soon as I target Android 11 (SDK 30) then I get this error. My guess is com.sun.mail dependencies need to be updated. I'm using the latest 1.6.5 and still doesn't work. So I suggest targeting SDK 29 for now and see if that helps.
My answer here, that is in-line with other answers (as that answer explains), does provide a solution (I'll skip to the content here, details can be read there);
The issue:
API level 30 adds a new (verifier) feature that verifies that all referenced code actually exists - or fails a build.
To resolve:
If you were providing the libraries manually via /app/libs/mail.jar, /app/libs/activation.jar, and /app/libs/additionnal.jar - you can go ahead and remove them; both google() and maven() repositories are enabled in Android projects, and the latest deps are available there. They include new META-INF files, so we'll also need to remove them from the build when we update the deps;
to your project-level gradle file (/build.gradle):
buildscript {
ext {
// ...
java_mail_version = "1.6.7"
}
// ...
}
// ...
to your app/module-level gradle file (/app/build.gradle):
//...
android {
// ...
packagingOptions {
resources {
excludes += '/META-INF/{AL2.0,LGPL2.1}'
excludes += '/META-INF/{NOTICE.md,LICENSE.md}' // <-- This line
}
}
}
// ...
dependencies {
// ...
// Dumb Email Sending
implementation "com.sun.mail:android-mail:$java_mail_version"
// REMOVE THESE - DEPS WILL DOWNLOAD AUTOMATICALLY
//implementation 'com.sun.mail:android-activation:1.6.7' // from 1.6.4
//implementation 'com.sun.mail:android-additionnal:1.6.7' // from 1.6.4
}
// ...
That's it, issue resolved on API Level 30 - and no more lugging the .jar files around (if you were).
I used Expo for my react-native app development.
Because of some packages not supported by Expo, I decided to eject my app from Expo.
I'm currently working on android studio, but stuck at this error.
java.lang.RuntimeException: Expo encountered a fatal error: java.net.ConnectException: Failed to connect to /192.168.0.6:19000
at host.exp.exponent.experience.BaseExperienceActivity$2.run(BaseExperienceActivity.java:206)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
If I navigate to BaseExperienceActivity.java:206,
...
// we don't ever want to show any Expo UI in a production standalone app
// so hard crash in this case
if (Constants.isStandaloneApp() && !isDebugModeEnabled()) {
throw new RuntimeException("Expo encountered a fatal error: " + errorMessage.developerErrorMessage());
}
...
I'm not using Expo start nor react-native run:android to run the app.
I'm running the app in Android Studio.
*Edited)
Below is my current build.gradle ./android/app
buildscript {
repositories {
google()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'io.fabric.tools:gradle:1.31.0'
}
}
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
apply plugin: 'devicefarm'
repositories {
maven { url 'https://maven.fabric.io/public' }
}
def safeExtGet(prop, fallback) {
rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
}
android {
compileSdkVersion safeExtGet("compileSdkVersion", 28)
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId '######'
minSdkVersion safeExtGet("minSdkVersion", 21)
targetSdkVersion safeExtGet("targetSdkVersion", 28)
versionCode 6
versionName '1.8.0'
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
// Deprecated. Used by net.openid:appauth
manifestPlaceholders = [
'appAuthRedirectScheme': 'host.exp.exponent'
]
}
dexOptions {
javaMaxHeapSize System.getenv("DISABLE_DEX_MAX_HEAP") ? null : "8g"
}
signingConfigs {
debug {
storeFile file('../debug.keystore')
}
release {
storeFile file(System.getenv("ANDROID_KEYSTORE_PATH") ?: "release-key.jks")
storePassword System.getenv("ANDROID_KEYSTORE_PASSWORD")
keyAlias System.getenv("ANDROID_KEY_ALIAS")
keyPassword System.getenv("ANDROID_KEY_PASSWORD")
}
}
buildTypes {
debug {
debuggable false
// debuggable true (Original)
// ext.enableCrashlytics = false
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
consumerProguardFiles 'proguard-rules.pro'
signingConfig signingConfigs.release
}
}
lintOptions {
abortOnError false
}
packagingOptions {
pickFirst "**"
}
}
devicefarm {
projectName System.getenv("DEVICEFARM_PROJECT_NAME")
devicePool System.getenv("DEVICEFARM_DEVICE_POOL")
executionTimeoutMinutes 40
authentication {
accessKey System.getenv("AWS_ACCESS_KEY_ID")
secretKey System.getenv("AWS_SECRET_ACCESS_KEY")
}
}
configurations.all {
resolutionStrategy {
force 'org.webkit:android-jsc:r245459'
}
}
// WHEN_PREPARING_SHELL_REMOVE_FROM_HERE
apply from: 'expo.gradle'
// WHEN_PREPARING_SHELL_REMOVE_TO_HERE
apply from: "../../node_modules/react-native-unimodules/gradle.groovy"
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.multidex:multidex:2.0.0'
// Our dependencies
implementation 'androidx.appcompat:appcompat:1.1.0'
// (Recommended) Add the Google Analytics dependency.
implementation 'com.google.firebase:firebase-analytics:17.2.1'
// Add the Firebase Crashlytics dependency.
implementation 'com.crashlytics.sdk.android:crashlytics:2.10.1'
// Our dependencies from ExpoView
// DON'T ADD ANYTHING HERE THAT ISN'T IN EXPOVIEW. ONLY COPY THINGS FROM EXPOVIEW TO HERE.
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.facebook.android:facebook-android-sdk:5.0.1'
implementation('com.facebook.android:audience-network-sdk:5.1.1') {
exclude module: 'play-services-ads'
}
compileOnly 'org.glassfish:javax.annotation:3.1.1'
implementation 'com.jakewharton:butterknife:10.2.0'
implementation 'de.greenrobot:eventbus:2.4.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
implementation 'com.google.android.gms:play-services-gcm:15.0.1'
implementation 'com.google.android.gms:play-services-analytics:16.0.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.android.gms:play-services-auth:15.0.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation "com.madgag.spongycastle:core:1.53.0.0"
implementation "com.madgag.spongycastle:prov:1.53.0.0"
debugImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta1'
// debugImplementation 'com.squareup.leakcanary:leakcanary-android:1.4-beta1'
releaseImplementation 'com.squareup.leakcanary:leakcanary-android-no-op:1.4-beta1'
implementation 'com.facebook.device.yearclass:yearclass:2.1.0'
implementation 'commons-io:commons-io:1.4'
implementation 'me.leolin:ShortcutBadger:1.1.4#aar'
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.0'
implementation 'commons-codec:commons-codec:1.10'
implementation 'com.segment.analytics.android:analytics:4.3.0'
implementation 'com.google.zxing:core:3.3.3'
implementation 'net.openid:appauth:0.4.1'
implementation 'com.airbnb.android:lottie:2.5.6'
implementation('io.nlopez.smartlocation:library:3.2.11') {
transitive = false
}
implementation "androidx.exifinterface:exifinterface:1.0.0"
implementation 'com.squareup.okio:okio:1.9.0'
implementation 'com.facebook.soloader:soloader:0.6.0'
// expo-file-system
implementation 'com.squareup.okhttp3:okhttp:3.10.0'
implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.10.0'
// Testing
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.0'
// We use a modified build of com.android.support.test:runner:1.0.1. Explanation in maven-test/README
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation "androidx.annotation:annotation:1.0.0"
androidTestImplementation 'com.google.code.findbugs:jsr305:3.0.0'
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'
androidTestImplementation 'com.azimolabs.conditionwatcher:conditionwatcher:0.2'
androidTestImplementation 'junit:junit:4.12'
androidTestImplementation 'org.mockito:mockito-core:1.10.19'
testImplementation 'org.robolectric:robolectric:3.8'
androidTestImplementation 'androidx.test:runner:1.1.0'
androidTestImplementation 'androidx.test:rules:1.2.0'
testImplementation 'androidx.test:runner:1.1.0'
testImplementation 'androidx.test:rules:1.2.0'
testImplementation 'junit:junit:4.12'
testImplementation 'org.mockito:mockito-core:1.10.19'
implementation('host.exp.exponent:expoview:36.0.0#aar') {
transitive = true
exclude group: 'com.squareup.okhttp3', module: 'okhttp'
exclude group: 'com.squareup.okhttp3', module: 'okhttp-urlconnection'
}
api 'org.webkit:android-jsc:r245459' // needs to be before react-native
api 'com.facebook.react:react-native:33.0.0'
addUnimodulesDependencies([
modulesPaths : [
'../../node_modules'
],
configuration: 'api',
target : 'react-native',
exclude : [
// You can exclude unneeded modules here, eg.
// 'unimodules-face-detector-interface',
// 'expo-face-detector'
// Adding a name here will also remove the package
// from auto-generated BasePackageList.java
]
])
}
// This has to be down here for some reason
apply plugin: 'com.google.gms.google-services'
I've got this problem too. I found that was occurred when property debuggable is true. Please check the build.gradle file in ./android/app/. Make sure that you pick the release version instead of debug and the property debuggable in release block is not exist or the value is false. Hope this would help you.
I'm using Retrofit 2 and OkHttp3 to data from server and I get
error while using Min_SDK 17 and my device's API is 17 also
I tried this answer :How to fix Expected Android API level 21+ but was 19 in Android
Also I tried this answer https://github.com/square/okhttp/issues/4597#issuecomment-461204144
but I get the same error .
my Gradle.Build class
apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
applicationId "some"
minSdkVersion 17
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
compileOptions {
targetCompatibility = "8"
sourceCompatibility = "8"
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v13:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation "com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0"
implementation "com.squareup.okhttp3:okhttp:3.11.0"
implementation "com.squareup.okhttp3:okhttp-urlconnection:3.11.0"
implementation "com.squareup.okhttp3:logging-interceptor:3.11.0"
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'net.alhazmy13.hijridatepicker:library:2.0.2'
implementation group: 'com.github.msarhan', name: 'ummalqura-calendar', version: '1.1.9'
implementation 'com.google.android.gms:play-services-maps:16.1.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
implementation 'com.google.android.gms:play-services-places:16.1.0'
implementation 'com.github.jaiselrahman:FilePicker:1.0.2'
implementation 'com.github.bumptech.glide:glide:4.5.0'
implementation 'com.squareup.okhttp3:okhttp:3.13.1'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.9.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'
}
my API Client
public class APIClient {
private static Retrofit retrofit;
private static OkHttpClient okHttpClient;
public static Retrofit getInstanceRetrofit(){
if(okHttpClient==null) {
initOkHttp();
}
if(retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(Const.URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
private static void initOkHttp() {
int REQUEST_TIMEOUT = 60;
OkHttpClient.Builder httpClient = new OkHttpClient().newBuilder()
.connectTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.readTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(REQUEST_TIMEOUT, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.addInterceptor(interceptor);
httpClient.addInterceptor(new Interceptor() {
#Override
public Response intercept(#NonNull Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.addHeader("Accept", "application/json")
.addHeader("Content-Type", "application/json");
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
okHttpClient = httpClient.build();
}
}
my Logs
1-03 06:09:07.850 2827-2827/some
E/AndroidRuntime: FATAL EXCEPTION: main
Process: some, PID: 2827
java.lang.ExceptionInInitializerError
at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:296)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:262)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:235)
at some.Network.APIClient.initOkHttp(APIClient.java:40)
at some.Network.APIClient.getInstanceRetrofit(APIClient.java:25)
at some.MvpImplementation.DropdownImpInteractor.getDropdowns(DropdownImpInteractor.java:18)
at some.MvpImplementation.DropdownImpPresenter.requestDropdowns(DropdownImpPresenter.java:21)
at some.Views.LoginActivity.onCreate(LoginActivity.java:87)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: Expected Android API level 21+ but was 19
at okhttp3.internal.platform.AndroidPlatform.buildIfSupported(AndroidPlatform.java:238)
at okhttp3.internal.platform.Platform.findPlatform(Platform.java:202)
at okhttp3.internal.platform.Platform.<clinit>(Platform.java:79)
at okhttp3.OkHttpClient.newSslSocketFactory(OkHttpClient.java:296)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:262)
at okhttp3.OkHttpClient.<init>(OkHttpClient.java:235)
at some.Network.APIClient.initOkHttp(APIClient.java:40)
at some.Network.APIClient.getInstanceRetrofit(APIClient.java:25)
at some.MvpImplementation.DropdownImpInteractor.getDropdowns(DropdownImpInteractor.java:18)
at some.MvpImplementation.DropdownImpPresenter.requestDropdowns(DropdownImpPresenter.java:21)
at some.Views.LoginActivity.onCreate(LoginActivity.java:87)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
The problem is that you have added OkHttp dependency twice.
In your build.gradle you have:
dependencies {
...
implementation "com.squareup.okhttp3:okhttp:3.11.0"
...
implementation "com.squareup.okhttp3:okhttp:3.13.1"
}
Starting with version 3.13.0 they removed support for Android < 5.
You just need to delete the
implementation "com.squareup.okhttp3:okhttp:3.13.1"
line and it should work fine
If you guys have still crash on Android 4.0 and above, here is quick solution:
implementation("com.squareup.retrofit2:retrofit:2.7.1")
implementation("com.squareup.okhttp3:okhttp:3.12.8") {
force = true
}
implementation "com.squareup.okhttp3:logging-interceptor:3.12.8"
Above code tested and verified on Android 4.4
Thanks
In your gradle file you have:
implementation "com.squareup.okhttp3:okhttp:3.11.0"
The docs say:
https://square.github.io/okhttp/
OkHttp works on Android 5.0+ (API level 21+) and on Java 8+.
The OkHttp 3.12.x branch supports Android 2.3+ (API level 9+) and Java 7+. These platforms lack support for TLS 1.2 and should not be used. But because upgrading is difficult we will backport critical fixes to the 3.12.x branch through December 31, 2020.
So you could try:
implementation "com.squareup.okhttp3:okhttp:3.12.0"
I'm using Google Cloud Speech to text. For some reason, It works only the first time. After that, this error keeps appearing. I'm stuck.
java.lang.NoSuchMethodError: No virtual method
build()Lcom/google/protobuf/GeneratedMessageLite; in class
Lcom/google/cloud/speech/v1/RecognitionConfig$Builder; or its super
classes (declaration of
'com.google.cloud.speech.v1.RecognitionConfig$Builder'
build.gradle module app
apply plugin: 'com.android.application'
apply plugin: 'com.google.protobuf'
apply plugin: 'com.jakewharton.butterknife'
ext {
grpcVersion = '1.4.0' }
android {
compileSdkVersion 28
defaultConfig {
applicationId "app.android.com.colconvert"
minSdkVersion 21
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.2'
} }
protobuf {
protoc {
artifact = 'com.google.protobuf:protoc:3.3.0'
}
plugins {
javalite {
artifact = "com.google.protobuf:protoc-gen-javalite:3.0.0"
}
grpc {
artifact = "io.grpc:protoc-gen-grpc-java:${grpcVersion}"
}
}
generateProtoTasks {
all().each { task ->
task.plugins {
javalite {}
grpc {
// Options added to --grpc_out
option 'lite'
}
}
}
} }
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.2'
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'
implementation 'com.intellij:annotations:+#jar'
implementation 'com.jakewharton:butterknife:10.1.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.1.0'
// gRPC
implementation "io.grpc:grpc-okhttp:$grpcVersion"
// implementation "io.grpc:grpc-protobuf-lite:$grpcVersion"
implementation "io.grpc:grpc-stub:$grpcVersion"
implementation 'javax.annotation:javax.annotation-api:1.2'
protobuf 'com.google.protobuf:protobuf-java:3.3.1'
implementation group: 'com.google.api.grpc', name: 'grpc-google-cloud-speech-v1', version: '0.1.13'
// OAuth2 for Google API
implementation('com.google.auth:google-auth-library-oauth2-http:0.7.0') {
exclude module: 'httpclient'
}
implementation 'com.android.support:multidex:1.0.0'
}
I think there is a problem with the version that you are using. I would recommend using the latest version like the following.
implementation group: 'com.google.api.grpc', name: 'grpc-google-cloud-speech-v1', version: '1.10.0'
Hope that helps!
I have been working on a project for months without issues. Just today re-opened the project in Android Studio and started getting the error:
Gradle sync failed: Failed to notify project evaluation listener.
I already tried this and this, without success.
I also cleaned cache, rebuilt project, restarted my pc, uninstalled and reinstalled Android Support and Google libraries in SDK, and tried with Invalidate Cache and restart. None of these things worked.
And I'm using Android Studio 2.1.1, just in case.
I hope someone could help me fix this issue. Thanks in advance.
LOG:
Caused by: org.gradle.internal.event.ListenerNotificationException: Failed to notify project evaluation listener.
at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:55)
at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:79)
at org.gradle.internal.event.BroadcastDispatch.dispatch(BroadcastDispatch.java:30)
at org.gradle.messaging.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:93)
at com.sun.proxy.$Proxy10.afterEvaluate(Unknown Source)
at org.gradle.configuration.project.LifecycleProjectEvaluator.notifyAfterEvaluate(LifecycleProjectEvaluator.java:67)
... 94 more
Caused by: java.lang.StackOverflowError
at com.google.common.base.Objects.hashCode(Objects.java:78)
at com.android.build.gradle.internal.dependency.LibraryDependencyImpl.hashCode(LibraryDependencyImpl.java:145)
at com.google.common.collect.AbstractMapBasedMultimap.put(AbstractMapBasedMultimap.java:192)
at com.google.common.collect.AbstractListMultimap.put(AbstractListMultimap.java:100)
at com.google.common.collect.ArrayListMultimap.put(ArrayListMultimap.java:66)
at com.android.build.gradle.internal.DependencyManager.addDependency(DependencyManager.java:807)
at com.android.build.gradle.internal.DependencyManager.addDependency(DependencyManager.java:855)
at com.android.build.gradle.internal.DependencyManager.addDependency(DependencyManager.java:855)
at com.android.build.gradle.internal.DependencyManager.addDependency(DependencyManager.java:855)
2016-05-29 15:34:00,668 [ 193987] WARN - nal.AbstractExternalSystemTask - Failed to notify project evaluation listener.
com.intellij.openapi.externalSystem.model.ExternalSystemException: Failed to notify project evaluation listener.
at org.jetbrains.plugins.gradle.service.project.AbstractProjectImportErrorHandler.createUserFriendlyError(AbstractProjectImportErrorHandler.java:106)
at org.jetbrains.plugins.gradle.service.project.BaseProjectImportErrorHandler.getUserFriendlyError(BaseProjectImportErrorHandler.java:158)
at org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension.getUserFriendlyError(BaseGradleProjectResolverExtension.java:457)
at org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension.getUserFriendlyError(AbstractProjectResolverExtension.java:158)
at com.android.tools.idea.gradle.project.AndroidGradleProjectResolver.getUserFriendlyError(AndroidGradleProjectResolver.java:350)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:373)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver$ProjectConnectionDataNodeFunction.fun(GradleProjectResolver.java:339)
at org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper.execute(GradleExecutionHelper.java:230)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:97)
at org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.resolveProjectInfo(GradleProjectResolver.java:65)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:41)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl$1.produce(RemoteExternalSystemProjectResolverImpl.java:37)
at com.intellij.openapi.externalSystem.service.remote.AbstractRemoteExternalSystemService.execute(AbstractRemoteExternalSystemService.java:59)
at com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolverImpl.resolveProjectInfo(RemoteExternalSystemProjectResolverImpl.java:37)
at com.intellij.openapi.externalSystem.service.remote.wrapper.ExternalSystemProjectResolverWrapper.resolveProjectInfo(ExternalSystemProjectResolverWrapper.java:49)
at com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask.doExecute(ExternalSystemResolveProjectTask.java:51)
at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:138)
at com.intellij.openapi.externalSystem.service.internal.AbstractExternalSystemTask.execute(AbstractExternalSystemTask.java:124)
at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$3.execute(ExternalSystemUtil.java:419)
at com.intellij.openapi.externalSystem.util.ExternalSystemUtil$4$2.run(ExternalSystemUtil.java:500)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:563)
at com.intellij.openapi.progress.impl.CoreProgressManager$2.run(CoreProgressManager.java:142)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:446)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:392)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:127)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:126)
at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:366)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
at org.jetbrains.ide.PooledThreadExecutor$1$1.run(PooledThreadExecutor.java:55)
2016-05-29 15:34:00,683 [ 194002] WARN - radle.project.ProjectSetUpTask -
2016-05-29 15:34:00,683 [ 194002] INFO - radle.project.ProjectSetUpTask - Failed to notify project evaluation listener.
Consult IDE log for more details (Help | Show Log)
2016-05-29 15:34:00,683 [ 194002] INFO - ls.idea.gradle.GradleSyncState - Sync with Gradle for project 'IconShowcase' failed: Failed to notify project evaluation listener.
Consult IDE log for more details (Help | Show Log)
2016-05-29 15:34:00,902 [ 194221] INFO - #com.jetbrains.cidr.lang - Clearing symbols finished in 0 s.
2016-05-29 15:34:00,969 [ 194288] INFO - #com.jetbrains.cidr.lang - Loading symbols finished in 0 s.
2016-05-29 15:34:01,016 [ 194335] INFO - #com.jetbrains.cidr.lang - Building symbols finished in 0 s.
2016-05-29 15:34:01,016 [ 194335] INFO - #com.jetbrains.cidr.lang - Saving symbols finished in 0 s.
PROJECT STRUCTURE
app build.gradle
apply plugin: 'com.android.application'
repositories {
maven { url "https://jitpack.io" }
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
lintOptions {
abortOnError false
}
defaultConfig {
applicationId "jahirfiquitiva.apps.iconshowcase.sample"
minSdkVersion 16
targetSdkVersion 23
versionCode 10
versionName "1.0"
generatedDensities = []
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
sourceSets {
main {
res.srcDirs = [
'src/main/res',
'src/main/res/drawable',
'src/main/res/drawable/dashboard',
'src/main/res/drawable/designer',
'src/main/res/drawable/icon_pack',
'src/main/res/drawable/launchers_icons',
'src/main/res/drawable/widgets',
'src/main/res/values',
'src/main/res/values/icon_pack',
'src/main/res/values/configuration'
]
}
}
buildTypes {
release {
minifyEnabled false
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
themeMode {} //themeMode for testing
standard {} //standard testing without themeMode stuff
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0'
compile project(':library')
}
library build.gradle
buildscript {
repositories {
mavenCentral()
}
}
apply plugin: 'com.android.library'
repositories {
mavenCentral()
maven { url "https://jitpack.io" }
}
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
lintOptions {
abortOnError false
}
defaultConfig {
minSdkVersion 16
targetSdkVersion 23
versionCode 10
versionName "1.0"
generatedDensities = []
}
aaptOptions {
additionalParameters "--no-version-vectors"
}
sourceSets {
main {
res.srcDirs = [
'src/main/res',
'src/main/res/drawable',
'src/main/res/drawable/dashboard',
'src/main/res/drawable/designer',
'src/main/res/drawable/icon_pack',
'src/main/res/drawable/launchers_icons',
'src/main/res/drawable/splash_screens',
'src/main/res/drawable/widgets',
'src/main/res/layout',
'src/main/res/layout/activities',
'src/main/res/layout/extras',
'src/main/res/layout/items',
'src/main/res/layout/sections',
'src/main/res/layout/widgets',
'src/main/res/values/icon_pack',
'src/main/res/values/configuration',
'src/main/res/values/texts'
]
}
}
buildTypes {
release {
minifyEnabled false
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
aaptOptions {
noCompress 'zip', 'komp', 'klwp', 'kwgt', 'klck', 'kwch'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0#aar'
compile 'com.android.support:support-v4:23.4.0#aar'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:cardview-v7:23.4.0#aar'
compile 'com.android.support:recyclerview-v7:23.4.0#aar'
compile 'com.android.support:palette-v7:23.4.0#aar'
compile 'com.android.support:gridlayout-v7:23.4.0'
compile 'com.android.support:customtabs:23.4.0'
//Material Dialogs
compile('com.github.afollestad.material-dialogs:core:0.8.5.9#aar') {
transitive = true
}
//Material Drawer
compile('com.mikepenz:materialdrawer:5.2.7#aar') {
transitive = true
}
//OkHttp
compile 'com.squareup.okhttp3:okhttp:3.3.1'
//Glide Library - Image Loading Lib
compile 'com.github.bumptech.glide:glide:3.8.0-SNAPSHOT'
//Sectioned RecyclerView
compile('com.afollestad:sectioned-recyclerview:0.2.2') {
transitive = true
}
compile 'com.truizlop.sectionedrecyclerview:library:1.1.0'
//Muzei API
//noinspection GradleDynamicVersion
compile 'com.google.android.apps.muzei:muzei-api:2.+'
//Circular Image View
compile 'de.hdodenhof:circleimageview:2.0.0'
//RecyclerView Fast Scroller
compile 'com.github.pluscubed:recycler-fast-scroll:0.3.1#aar'
//Donations Lib
compile 'org.sufficientlysecure:donations:2.4'
//License Checker Lib
compile 'com.github.javiersantos:PiracyChecker:0.0.2'
//Required for better Zooper setup
compile 'io.reactivex:rxandroid:1.1.0'
//Required for Kustom support.
//noinspection GradleDynamicVersion
compile 'org.bitbucket.frankmonza:kustomapi:+'
}
settings.gradle
include ':app', ':library'
I had a similar problem when I moved to a higher level of gradle. Found the answer here. Try changing the gradle level
In my case, this version helped
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
}
and this gradele version throws mistakes
'com.android.tools.build:gradle:2.2.2'
'com.android.tools.build:gradle:3.0.0'
Just do not forget to change distributionUrl in gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-4.0-milestone-1-all.zip
Fixed it by changing the MaterialDialogs lib version to
compile('com.afollestad.material-dialogs:core:0.8.5.9#aar') { transitive = true }
I downloaded an old repository from GitHub and tried to update some versions. Then got this error. After I reverted back
distributionUrl=https\://services.gradle.org/distributions/gradle-5.1-all.zip
as #Kamila suggested, the error disappeared.