【Android】Hilt + KSP で error.NonExistentClass を解決するヒント - Protobuf / SQLDelight / ViewBinding / AIDL

見かけましたよね。

以下に似たようなエラー。


e: [ksp] InjectProcessingStep was unable to process 'RemoteUnfoldTransitionReceiver(boolean,java.util.concurrent.Executor)' because 'error.NonExistentClass' could not be resolved.

Dependency trace:
    => element (CLASS): com.android.systemui.unfold.progress.RemoteUnfoldTransitionReceiver
    => type (ERROR superclass): error.NonExistentClass

If type 'error.NonExistentClass' is a generated type, check above for compilation errors that may have prevented the type from being generated. Otherwise, ensure that type 'error.NonExistentClass' is on your classpath.
e: [ksp] InjectProcessingStep was unable to process 'UnfoldTransitionProgressForwarder()' because 'error.NonExistentClass' could not be resolved.

Dependency trace:
    => element (CLASS): com.android.systemui.unfold.progress.UnfoldTransitionProgressForwarder
    => type (ERROR superclass): error.NonExistentClass

If type 'error.NonExistentClass' is a generated type, check above for compilation errors that may have prevented the type from being generated. Otherwise, ensure that type 'error.NonExistentClass' is on your classpath.
e: [ksp] ComponentProcessingStep was unable to process 'com.android.systemui.unfold.RemoteUnfoldSharedComponent' because 'error.NonExistentClass' could not be resolved.

Dependency trace:
    => element (CLASS): com.android.systemui.unfold.progress.RemoteUnfoldTransitionReceiver
    => type (ERROR superclass): error.NonExistentClass

If type 'error.NonExistentClass' is a generated type, check above for compilation errors that may have prevented the type from being generated. Otherwise, ensure that type 'error.NonExistentClass' is on your classpath.
e: Error occurred in KSP, check log for detail

私は、SDKバージョンアップ時に SQLDelight で出会いましたが以下で回避。


// bottom of app/build.gradle.kts

androidComponents {
  onVariants(selector().all()) { variant ->
    afterEvaluate {
      val capName = variant.name.capitalize()
      tasks.getByName<KotlinCompile>("ksp${capName}Kotlin") {
        setSource(tasks.getByName("generate${capName}DatabaseInterface").outputs)
      }
    }
  }
}

👉 [ksp] InjectProcessingStep was unable to process a class which extends Binder Stub because 'error.NonExistentClass' could not be resolved. · Issue #4158 · google/dagger

こんな「とりあえず回避」ってのよくありますが

対応コードが溜まっていくと後々意味不明になるので

なんか嫌ですけど、

仕方ないんですよね。

👉 SqlDelight inconsistency with KSP · Issue #5473 · sqldelight/sqldelight
👉 KSP Compilation Failure: Unresolved `error.NonExistentClass` during `MarketDaoImpl` and `LocalDatasourceModule` processing · Issue #2092 · google/ksp
👉 SQLDelight 2.0 Tasks · Issue #2694 · sqldelight/sqldelight


Hilt で KSP の依存関係の設定 (build.gradle.kts)

kapt から KSP に移行しようとしてハマる。

 

🚀 Dagger + KSP

今回は使わなったが動く。


plugins {
  id("org.jetbrains.kotlin.android") version "1.9.0"
  id("com.google.devtools.ksp") version "1.9.0-1.0.12"
}

dependencies {
  ksp("com.google.dagger:dagger-compiler:2.48") // Dagger compiler
  ksp("com.google.dagger:hilt-compiler:2.48")   // Hilt compiler
}

👉 Dagger KSP hatena-bookmark

 

🚀 Hilt + kapt


// build.gradle.kts (Project)

plugins {
  id("com.google.dagger.hilt.android") version "2.44" apply false
}


// build.gradle.kts (Module)

plugins {
  kotlin("kapt")
  id("com.google.dagger.hilt.android")
}

dependencies {
  implementation("com.google.dagger:hilt-android:2.44")
  kapt("com.google.dagger:hilt-android-compiler:2.44")
}

kapt {
  correctErrorTypes = true
}

👉 Hilt を使用した依存関係の注入  |  Android デベロッパー  |  Android Developers hatena-bookmark

 

🚀 Hilt + KSP


// build.gradle.kts (Project)

plugins {
  id("com.google.devtools.ksp") version "1.8.10-1.0.9" apply false
  id("com.google.dagger.hilt.android") version "2.44" apply false
}


// build.gradle.kts (Module)

plugins {
  id("com.google.devtools.ksp")
  id("com.google.dagger.hilt.android")
}

dependencies {
  implementation("com.google.dagger:hilt-android:2.44")
  ksp("com.google.dagger:hilt-android-compiler:2.44")
}

👉 kapt から KSP に移行する  |  Android デベロッパー  |  Android Developers hatena-bookmark

👉 Revisions · Hilt + kapt → KSP hatena-bookmark

 

🚀 まとめ

Hilt で公式リファレンスを見ながら、kapt → KSP と順番に変化させていけばスムーズに対応できたのに、Dagger KSP ページを見ながら進んだのがハマった原因。

Version Catalog を使っていくことになりそうなので、抜粋しておく。




【OpenAI】Kotlin OkHttp で Server-Sent Events (SSE)

ChatGPT API で stream 受信したいですよね。

stream boolean Optional Defaults to false

If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only server-sent events as they become available, with the stream terminated by a data: [DONE] message.

👉 API Reference - OpenAI API hatena-bookmark

簡単にできそうなのでやってみました。

 

📡 curl

curl で簡単に取得できる。


curl "https://api.openai.com/v1/chat/completions" \
  -H "accept: text/event-stream" \
  -H "authorization: Bearer $OPENAI_API_KEY" \
  -H "content-type: application/json" \
  -d '{
    "model": "gpt-3.5-turbo",
    "messages": [{"role": "user", "content": "Server-Sent Events とは"}],
    "stream": true
  }'


...

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"て"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"います"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{"content":"。"},"index":0,"finish_reason":null}]}

data: {"id":"chatcmpl-7OQ1xuBFfam8Ct","object":"chat.completion.chunk","created":1686054286,"model":"gpt-3.5-turbo","choices":[{"delta":{},"index":0,"finish_reason":"stop"}]}

data: [DONE]

パースはだるそうですが、取得はできてるようです!

では、いざ、Kotlin で。

 

📡 okhttp-sse

壊れてるのか何なのか微妙。


testImplementation("com.squareup.okhttp3:okhttp-sse:4.11.0")

👉 okhttp/okhttp-sse at master · square/okhttp · GitHub hatena-bookmark

現在の安定版 4.11.0 ではあやしい。

5.0.0-alpha.11 ではまあまあ動いてるのでそれで。



SSEは、日本語で表現するとサーバ送信イベントと表現されるもので、サーバからクライアントに対してリアルタイムでイベントを送信することができる機能です。 コネクションを張っておいて、サーバからイベントを好きなタイミングで送れるイメージです

 

📡 まとめ

カンファレンスでの公演資料とか、時間が経つと、まあ動かないこと多いですよね!


👉 Server-Sent Events in Android (with Node.js) | by Rahul Ray | Jun, 2023 | ProAndroidDev hatena-bookmark


【Retrofit】データクラス エンティティ フィールド名の付け替え @SerializedName @Json @SerialName

同じ Retrofit を使うにしても、パーサーによってアノテーション記述が変わるので、ググると無駄に時間がかかってしまう。

【Retrofit】データクラス エンティティ フィールド名の付け替え @SerializedName @Json @SerialName

 

🔄 Gson


data class User (
    @SerializedName("id")
    long userId;
    @SerializedName("fullName")
    String name;
)

👉 gson/UserGuide.md at master · google/gson hatena-bookmark

 

🔄 Moshi


@JsonClass(generateAdapter = true)
data class User (
    @Json(name = "id")
    long userId;
    @@Json(name = "fullName")
    String name;
)

👉 square/moshi: A modern JSON library for Kotlin and Java. hatena-bookmark

 

🔄 kotlinx.serialization


@Serializable
data class User (
    @SerialName("id")
    long userId;
    @SerialName("fullName")
    String name;
)

👉 kotlinx.serialization/basic-serialization.md at master · Kotlin/kotlinx.serialization hatena-bookmark

 

🔄 まとめ

初めて使うときは混乱するだろうと思います。

今となっては、JSONパーサーは、Kotlin 内蔵の kotlinx.serialization を使いたいですね。

👉 「Kotlinx Json」の登場でサードパーティJSONライブラリは不要となる。 hatena-bookmark


【AndroidStudio】Debug Console の ログ フィルター がないので fold する方法

Retrofit でテストしてみたらログが見づらい。

WARNING: An illegal reflective access operation has occurred

何なんですかね。

まずこれ。


WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by retrofit2.Platform (file:/Users/mersan/.gradle/caches/modules-2/files-2.1/com.squareup.retrofit2/retrofit/2.8.0/53fa357bd7538d2c4872bddf33654f113cf6652b/retrofit-2.8.0.jar) to constructor java.lang.invoke.MethodHandles$Lookup(java.lang.Class,int)
WARNING: Please consider reporting this to the maintainers of retrofit2.Platform
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release

Groovy と Java のバージョンによる相性なのか、なんなのか、よくわからん。

👉 [GROOVY-8339] Fix warning "An illegal reflective access operation has occurred" - ASF JIRA hatena-bookmark
👉 [GROOVY-9103] CLONE - CLONE - Fix warning "An illegal reflective access operation has occurred" - ASF JIRA hatena-bookmark

これについて、Jake さんは問題ないと言っています。

The reflection works around a bug in the JDK which was fixed in 14 but it's only used for default methods. As it's only a warning, it's not preventing your call from working.

👉 Illegal reflective access · Issue #3341 · square/retrofit hatena-bookmark

あと、Retrofit のログも見づらい。


Apr 12, 2023 10:19:16 AM okhttp3.internal.platform.Platform log
INFO: Server: cloudflare
Apr 12, 2023 10:19:16 AM okhttp3.internal.platform.Platform log
INFO: CF-RAY: 7b67a3d78f9f2647-NRT
Apr 12, 2023 10:19:16 AM okhttp3.internal.platform.Platform log
INFO: alt-svc: h3=":443"; ma=86400, h3-29=":443"; ma=86400
Apr 12, 2023 10:19:16 AM okhttp3.internal.platform.Platform log
INFO: <-- END HTTP

まあ、Level.NONE にすれば消えるのだが、通信状態は見えなくなるし。


val interceptor = HttpLoggingInterceptor().apply {
  level = if (BuildConfig.DEBUG) Level.BODY else Level.NONE
}

👉 【Retorofit】コピペで使える NetworkModule【Dagger Hilt】 hatena-bookmark

 

■ Filter messages in Android Studio debug console

こんな機能あったんですね。

Right click on the line you want to hide, on the popup menu click "Fold lines like this". You'll be prompted a window where you can edit the folded lines content.

Ps. Folded lines content work the way contains string method does.

👉 Filter messages in Android Studio debug console - Stack Overflow hatena-bookmark

隠したい行で右クリックから Fold Lines Like This です。

折り畳まれて、とりあえずは見やすくなりました!

まだまだ使ったことのない知らない機能がたくさんありますわあ。