LoginSignup
0
0

Android+RetrofitでHTTP通信するアプリの作り方(その2)

Last updated at Posted at 2024-02-25

Android+RetrofitでHTTP通信するアプリの作り方(その2)

前回の記事でサーバーと通信ができるようになりました。

ここから作り込んでいきます。

ですが、あれこれ組み込む前に、ひとつ仕組みを組み込みます。

Dependency Injectionです。

最初から組み込んでおくと、後々楽ができます。

目次

記事を書く上で参考にした資料

本家サイト。

Hiltとは

https://dagger.dev/hilt/

Hilt provides a standard way to incorporate Dagger dependency injection into an Android application.

  • AndroidアプリにDaggerを取り込む、ということ

準備

以下の準備が必要です。

  1. KSPの導入
  2. Hiltのdependencyの追加
  3. Applicationクラスの修正
  4. Manifestの修正
  5. Actiity、Fragmentの修正

順に説明します。

KSPの導入

最初にKSPを追加しておきます。

Hiltの本家サイトにはkaptを使うよう記されていますが、より軽く動くKSPがリリースされています。

developer.android.comにもkaptからKSPの移行のガイドがあります。

なので、KSPを導入します。

最上位のbuild.gradleにKSPを追記する

plugins {
    id("com.google.devtools.ksp") version "1.9.22-1.0.17" apply false
}

KotlinのバージョンとKSPのバージョンは正しく対応させないとビルドできません。注意しましょう。

app/build.gradleにKSPを追記する

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

Hiltのdependencyの追加

https://dagger.dev/hilt/gradle-setupを参考に

最上位のbuild.gradleにHiltを追記する

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

app/build.gradle.ktsにHiltを追加する

plugins {
    id("com.google.dagger.hilt.android")
}
dependencies {
    ...
    // hilt
    implementation ("com.google.dagger:hilt-android:2.50")
    ksp ("com.google.dagger:hilt-compiler:2.50")
    // For instrumentation tests
    androidTestImplementation ("com.google.dagger:hilt-android-testing:2.50")
    kspAndroidTest ("com.google.dagger:hilt-compiler:2.50")
    // For local unit tests
    testImplementation ("com.google.dagger:hilt-android-testing:2.50")
    kspTest ("com.google.dagger:hilt-compiler:2.50")
    ...
}

annotationプロセッサーとしてKSPを使います。

Applicationの修正

アプリケーションクラスの定義に@HiltAndroidAppアノテーションを付加します。

@HiltAndroidApp
class MyApplication: Application() {
}

アプリケーションクラスがない場合は追加します。

Manifestの修正

アプリケーションクラスを追加したら、Manifestにnameを追加しておきます。

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    ...
    <application
        android:name=".MyApplication"
        ...
    >
        ...
    </application>
</manifest>

Hilt導入以前からアプリケーションクラスを利用していたなら、すでに追加済みのはずです。
その場合は、Manifestを修正する必要はありません。

Activity、Fragmentの修正

@AndroidEntryPointアノテーションを付加します。

@AndroidEntryPoint
class MainActivity : ComponentActivity() {
    ...
}

試しにビルド

プロジェクトをビルドできれば完成です。プロジェクトにHiltが導入されました。

リポジトリ

https://github.com/aburagirio/retrofitExample.git

ブランチpart2をcheck outしてください。
 

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0