LoginSignup

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

[kotlin]Retrofit2について

解決したいこと

kotlinで下記コードを入れるとエラー(logcat:java.lang.ExceptionInInitializerError)が発生するのですが解決策にお心当たりございましたらご教示いただけないでしょうか。参考書通りにコードを入力しても
アプリが起動せず困っております。
/////////////////////////////////////////////////////////////////////////////
companion object {
private val TAG = MainFragment::class.java.simpleName
private const val API_BASE_URL = "https://androidbook2020.keiji.io"
}

private val retrofit = Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .build()
private val api = retrofit.create(MastodonApi::class.java)

////////////////////////////////////////////////////////////////////////////

build.gradleは以下としています。
////////////////////////////////////////////////////////////////////////////
dependencies {
implementation 'androidx.core:core-ktx:1.6.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.3'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
implementation 'androidx.fragment:fragment-ktx:1.2.3'
implementation 'com.squareup.retrofit2:retrofit:2.7.1'
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.3"
}
/////////////////////////////////////////////////////////////////////////////

自分で試したこと

・次のコードを入れるとアプリがクラッシュし、このコードを入れない場合はアプリは動作しました。
private val retrofit = Retrofit.Builder()
.baseUrl(API_BASE_URL)
.build()

・次のサイトで調べた.applyを入れた方法でもダメでした。https://qiita.com/naoi/items/5036adc8d33638911deb
private val retrofit = Retrofit.Builder().apply {
baseUrl(API_BASE_URL)
}.build()
・android studioのversionが違うから動作していないのでしょうか。←これくらいしか心当たりがなく。

その他解決可能性向上のために以下サイトでも質問中です。
https://teratail.com/questions/362478
https://ja.stackoverflow.com/questions/82833/retrofit%e3%81%ab%e3%81%a4%e3%81%84%e3%81%a6

0

1Answer

implementation 'com.squareup.okhttp3:okhttp:4.9.1'
上記をコードすることで解決できました。皆様ありがとうございました。

0

Your answer might help someone💌