I am trying to perform network operation async in Kotlin. I read it you can do async using async function. I am getting below error, can anyone guess what could be the issue ?
Unresolved reference: async
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
async() {
val forecastWeather = ForecastRequest("302015").execute()
Log.d("Test", forecastWeather.toString())
}
}
ForecastRequest.kt
class ForecastRequest(val zipcode: String) {
companion object {
private val APP_ID = "XYZ"
private val URL = "http://api.openweathermap.org/data/2.5/" +
"forecast/daily?mode=json&units=metric&cnt=7"
private val COMPLETE_URL = "$URL&APPID=$APP_ID&q="
}
fun execute(): ForecastResponse {
val forecastJsonStr = java.net.URL(COMPLETE_URL + zipcode).readText()
return Gson().fromJson(forecastJsonStr, ForecastResponse::class.java)
}
}
Top level build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.1.2-4'
repositories {
maven { url 'https://maven.google.com' }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0-alpha2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url 'https://maven.google.com' }
jcenter()
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
Module level build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.williams.thirddemo"
minSdkVersion 23
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.google.code.gson:gson:2.8.1'
}
async is available inside kotlinx.couroutines
Make sure that you added the dependency in your gradle file:
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.1.1'
Also make sure that the async is called on a coroutine scrope such as GlobalScope.
val deferredResult = GlobalScope.async {
}
I see async function is available in anko library not Kotlin library itself. https://github.com/Kotlin/anko
I resolved by adding this dependency in build.gradle compile "org.jetbrains.anko:anko-commons:0.10.1" as this is not available in Kotlin itself.
I see that async is deprecated now, library suggests to use doAsync instead.
doAsync {
val forecastWeather = ForecastRequest("302015").execute()
uiThread {
Log.d("Test", forecastWeather.toString())
}
}
Different Kotlin libraries can have different implementations of async that do different things.
If you wanted the general async-await function from the core library, make sure you have a dependency to kotlinx.coroutines
if you are using Deferred , make sure you import kotlinx.coroutines.Deferred, there is also a chance you import firebase Deferred
Related
So, I'm trying to let jetpack compose run with a simple example, I have already updated my kotlin plugin to 1.4.0 and also updated all my build gradle with the jetpack compose documentation, but I got this error when compiling
java.lang.IncompatibleClassChangeError: Found interface
org.jetbrains.kotlin.backend.common.extensions.IrPluginContext, but
class was expected at
androidx.compose.plugins.kotlin.ComposeIrGenerationExtension.generate(ComposeIrGenerationExtension.kt:41)
I have also downloaded the canary version of Android studio
build.gradle project
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = "1.4.0-rc"
repositories {
google()
jcenter()
maven{
url "https://dl.bintray.com/kotlin/kotlin-eap/"
}
}
dependencies {
classpath "com.android.tools.build:gradle:4.0.1"
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven{
url "https://dl.bintray.com/kotlin/kotlin-eap/"
}
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
build.gradle app
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 30
buildToolsVersion "30.0.1"
defaultConfig {
applicationId "com.jetpackcompose"
minSdkVersion 22
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'
}
}
buildFeatures {
// Enables Jetpack Compose for this module
compose true
}
// Set both the Java and Kotlin compilers to target Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
composeOptions {
kotlinCompilerVersion kotlin_version
kotlinCompilerExtensionVersion "0.1.0-dev13"
}
}
dependencies {
implementation fileTree(dir: "libs", include: ["*.jar"])
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.1'
implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.ui:ui-core:0.1.0-dev13'
implementation 'androidx.ui:ui-tooling:0.1.0-dev13'
implementation 'androidx.ui:ui-layout:0.1.0-dev13'
implementation 'androidx.ui:ui-material:0.1.0-dev13'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).configureEach {
kotlinOptions {
jvmTarget = "1.8"
freeCompilerArgs += ["-Xallow-jvm-ir-dependencies", "-Xskip-prerelease-check"]
}
}
But I cant compile the app, I'm trying to run the basic example
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent{
sayHello()
}
}
#Preview
#Composable
fun sayHello(){
Text("Hello World")
}
}
Does anyone knows why this error is thrown ?
Using Kotlin version 1.4.10 instead of 1.4.20 solved my problem.
Try to update Compose version to 0.1.0-dev16. Looks like 0.1.0-dev13 isn't compatible with Kotlin 1.4-rc
I was having this problem on my released app so I decide to create a tester app and a new Firebase project to repeat my actions and I'm getting the same problems.
I'm just trying to read and write data to RealtimeDatabase of Firebase the same way that I'm doing since learn Firebase years ago.
The DatabaseReference.CompletionListener() is not being called neither the ValueEventListener.onDataChange() or ValueEventListener.onCancelled().
My code is being shown below:
MainActivity.kt
class MainActivity : AppCompatActivity() {
companion object {
const val TAG = "TAG-FOR-LOG"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val database = FirebaseDatabase.getInstance()
val ref = database.reference
ref.child("test2").setValue("This is a test", object : DatabaseReference.CompletionListener {
override fun onComplete(p0: DatabaseError?, p1: DatabaseReference) {
Log.d(TAG,"The error was $p0")
}
})
ref.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
val value = dataSnapshot.getValue(String::class.java)
Log.d(TAG, "Value is: $value")
}
override fun onCancelled(error: DatabaseError) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException())
}
})
}
}
app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.google.gms.google-services'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.cqsuzanotest"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.firebase:firebase-database:19.2.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
ext.kotlin_version = '1.3.61'
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
For this moment this problem occurrence on the released version but is for an activity not very important.
Just for complements, the logcat shows nothing.
EDIT: My google-services.json file is updated and my rules on Firebase project dashboard are:
{
"rules": {
".read": true,
".write": true
}
}
The problem was my router firewall.
I discovered running the program in my University network, it did run as well.
At home, I rebooted the router and the problem is gone.
I'm trying to embed Ktor in an Android Service in order to check remotely some assets on an app at some point.
I'm following the code in this tutorial
I get this error when I attempt to access the link for example on "192.168.2.105:7070":
04-20 14:50:58.523 29389-29389 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.mypackage.fetchingservice, PID: 29389
java.lang.NoClassDefFoundError:io.ktor.application.ApplicationEvents$subscribe$1
at io.ktor.application.ApplicationEvents.subscribe(ApplicationEvents.kt:18)
at io.ktor.server.engine.BaseApplicationEngine.<init>(BaseApplicationEngine.kt:29)
at io.ktor.server.engine.BaseApplicationEngine.<init>(BaseApplicationEngine.kt:15)
at io.ktor.server.netty.NettyApplicationEngine.<init>(NettyApplicationEngine.kt:16)
at io.ktor.server.netty.Netty.create(Embedded.kt:10)
at io.ktor.server.netty.Netty.create(Embedded.kt:8)
at io.ktor.server.engine.EmbeddedServerKt.embeddedServer(EmbeddedServer.kt:50)
at io.ktor.server.engine.EmbeddedServerKt.embeddedServer(EmbeddedServer.kt:40)
at io.ktor.server.engine.EmbeddedServerKt.embeddedServer$default(EmbeddedServer.kt:27)
at com.hirschandmann.magickservice.KtorFetchService.onCreate(KtorFetchService.kt:30)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2761)
at android.app.ActivityThread.access$1800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1386)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:935)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:730)
Here's the code. Service is registered in the manifest and I launch it from adb using:
adb shell am startservice com.mypackage.service/.KtorFetchService
class KtorFetchService : Service() {
override fun onBind(intent: Intent?): IBinder {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
private val HTTP_PORT = 7070
override fun onCreate() {
embeddedServer(Netty, HTTP_PORT) {
routing {
get("/") {
call.respondText("My Example Fetch", ContentType.Text.Html)
}
}
}.start(wait = true)
super.onCreate()
}
}
Here's the module gradle file:
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.hirschandmann.magickservice"
minSdkVersion 21
targetSdkVersion 27
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
pickFirst 'META-INF/*'
}
}
repositories {
jcenter()
mavenCentral()
maven { url "http://dl.bintray.com/kotlin/ktor" }
maven { url "https://dl.bintray.com/kotlin/kotlinx" }
}
configurations {
ktlint
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation'com.android.support:appcompat-v7:27.1.1'
testImplementation'junit:junit:4.12'
androidTestImplementation'com.android.support.test:runner:1.0.1'
androidTestImplementation'com.android.support.test.espresso:espresso-core:3.0.1'
// AutoValue
compileOnly "com.google.auto.value:auto-value:1.5.2"
annotationProcessor "com.google.auto.value:auto-value:1.5.2"
// ktlint
ktlint "com.github.shyiko:ktlint:0.15.0"
implementation'com.github.hkk595:Resizer:v1.5'
implementation'com.jrummyapps:android-shell:1.0.1'
implementation'org.nanohttpd:nanohttpd:2.3.1'
implementation"io.ktor:ktor:$ktor_version" // ktor dependency
implementation"io.ktor:ktor-server-netty:$ktor_version"
}
task ktlint(type: JavaExec, group: "verification") {
description = "Check Kotlin code style."
classpath = configurations.ktlint
main = "com.github.shyiko.ktlint.Main"
args "src/**/*.kt"
//args "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
}
check.dependsOn ktlint
androidExtensions {
experimental = true
}
Here's the project's gradle file:
buildscript {
ext.kotlin_version = '1.2.40'
ext.ktor_version = '0.9.1'
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
plugins {
id "io.gitlab.arturbosch.detekt" version "1.0.0.RC6-3"
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
detekt {
version = "1.0.0.RC6-3"
profile("main") {
input = "$projectDir/app/src/main/java"
config = "$projectDir/default-detekt-config.yml"
filters = ".*test.*,.*/resources/.*,.*/tmp/.*"
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
The device is an Odroid C2 with Android 5.1.1 (API 22)
I'm using Android studio 3.1 and JRE 1.8 running on a MacOS 10.13.3.
The error is caused by the following line in ktor ApplicationEvents.kt:18
handlers.computeIfAbsent(definition) { LockFreeLinkedListHead() }.addLast(registration)
This causes it to fail as far as ConcurrentHashMap.computeIfAbsent and java.util.function.Function has been initially introduced in API level 24 (proof).
Note that ktor server was never intended to run on android and originally targeted to servers with JDK8
I've been running a Netty-based Ktor server on Android 5+ for a while, and I've created this minimal repo to demo it: https://github.com/gnarea/minimal-ktor-server-android
i am integrating "Strip" payment method in my app but when i add the stripe dependence compile 'com.stripe:stripe-android:1.0.3' also try compile 'com.stripe:stripe-android:+' an error occur that is
i see many answer for realm Re-linker like using
compile 'com.getkeepsafe.relinker:relinker:1.2.1'
Compile 'io.reactivex:rxjava:1.1.0' but the problem is still exist
this is my Realm application class
public class WifiExploreApplication extends Application {
#Override
public void onCreate(){
super.onCreate();
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
.name("com.holygon.zaingz.alu").build();
Realm.setDefaultConfiguration(realmConfiguration)
}
}
this is my gradle
apply plugin: 'com.android.application'
android {
compileSdkVersion 'Google Apis:Google Apis:23'
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.example.wifiexplorer"
minSdkVersion 19
targetSdkVersion 23
versionCode 1
multiDexEnabled true
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
productFlavors {
}
}
repositories {
maven { url "https://jitpack.io" }
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:cardview-v7:23.2.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.github.sembozdemir:ViewPagerArrowIndicator:1.0.0'
compile 'de.hdodenhof:circleimageview:2.0.0'
compile 'com.android.support:multidex:1.0.0'
compile "com.android.support:support-v4:23.0.0"
compile 'com.google.android.gms:play-services:8.4.0'
compile 'com.getkeepsafe.relinker:relinker:1.2.1'
compile 'com.stripe:stripe-android:1.0.3'
}
dependencies {
repositories {
mavenCentral()
}
compile 'com.sothree.slidinguppanel:library:3.3.0'
}
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
apply plugin: 'realm-android'
and
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
classpath "io.realm:realm-gradle-plugin:0.88.2"
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
before using stripe all the things going well but when i use strip it will show error
any suggestion will appreciate able..
You're using the AAR Gradle Plugin version of Realm (as in 0.88.0+, but an outdated one, considering the latest is 1.1.0) but you're never actually calling apply plugin: 'realm-android' in your build.gradle file.
You're also missing this from your application class
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
Oh by the way, you probably should use modularized version of Google Play Services so that you wouldn't even need Multi-Dex in the first place.
I am converting one of my apps to Gradle and would like to use the new build flavor features to have a paid and a free ad based flavor.
I want only the ad based version to depend on the admob SDK.
My build file looks like this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
android {
compileSdkVersion 18
buildToolsVersion "18.0.1"
defaultConfig {
minSdkVersion 10
targetSdkVersion 18
}
productFlavors {
Pro {
packageName "de.janusz.journeyman.zinsrechner.pro"
}
Free {
dependencies {
}
}
}
}
dependencies {
compile 'com.android.support:support-v4:18.0.+'
compile 'com.actionbarsherlock:actionbarsherlock:4.4.0#aar'
compile fileTree(dir: 'libs', include: '*.jar')
}
Is there a way to configure the dependency in the free product flavor to have its own libs folder that is merged with the main libs folder that contains general libraries for both flavors?
If this is possible how would I define this folder?
To define a flavor specific dependency you can use proCompile instead of compile in your dependency section. When you run gradle properties you get an overview of automatic created configurations.
The correct build file looks like this:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.2.3'
}
}
apply plugin: 'com.android.application'
repositories {
mavenCentral()
}
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
minSdkVersion 10
targetSdkVersion 22
}
productFlavors {
pro {
packageName "de.janusz.journeyman.zinsrechner.pro"
}
free { }
}
}
dependencies {
compile 'com.android.support:support-v4:22.2.0'
freeCompile 'com.google.android.gms:play-services-ads:7.5.0'
}
Fast forward to mid-2018. You will need to add flavorDimensions.
android {
...
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "dimensionName"
productFlavors {
pro {
dimension "dimensionName"
}
free {
dimension "dimensionName"
}
}
}
dependencies {
implementation 'com.android.support:support-v4:22.2.0'
freeImplementation 'com.google.android.gms:play-services-ads:15.0.1'
}
Also, take note:
Configuration 'compile' is obsolete and has been replaced with
'implementation' and 'api'. It will be removed at the end of 2018. For
more information see:
http://d.android.com/r/tools/update-dependency-configurations.html
Simple:
dependencies {
....
....
gradle.startParameter.getTaskNames().each { task ->
if(task.contains("free")) {
implementation 'com.google.android.gms:play-services-ads:17.2.0'
}
}
....
....
}
or just:
FreeImplementation 'com.google.android.gms:play-services-ads:17.2.0'
You need to manually add configuration for each flavor. Example
configurations {
proCompile
freeCompile
}
dependencies {
compile 'com.parse.bolts:bolts-tasks:1.3.0'
proCompile 'com.android.support:design:23.1.1'
freeCompile 'com.parse:parse-android:1.12.0'
}
Edit: I recommend using one of the other techniques!
An alternative to the accepted answer is this:
ext {
flavorType = ""
}
gradle.startParameter.getTaskNames().each { task ->
if(task.contains("flavor1")){
flavorType = "flavor1"
} else if (task.contains("flavor2")){
flavorType = "flavor2"
} else {
flavorType = "flavor3"
}
}
if(flavorType == 'flavor1' || flavorType == 'flavor2') {
compile 'com.android.support:support-v4:18.0.+'
}
If you use Gradle with Kotlin, dependencies for custom flavors can be added as follows:
dependencies {
"freeImplementation"("com.google.android.gms:play-services-ads:7.5.0")
}