79192446

Date: 2024-11-15 12:55:20
Score: 1.5
Natty:
Report link

I think i have solution for query. I've tried this way it will work for you.

here are some steps of implementation of Dependency Injection.

1. Add Hilt Dependencies Add the necessary dependencies in your build.gradle file:.

Add this into your app build.gradle.kts file

dependencies {
    ksp("com.google.dagger:hilt-compiler:2.48")  // for dagger
    implementation("com.google.dagger:hilt-android:2.48") // for hilt

    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1") // viewmodel

    implementation("com.squareup.retrofit2:converter-gson:2.9.0") // retrofit 
    implementation("com.google.code.gson:gson:2.10.1") // gson
}

And add this into your project build.gradle.kts file

    plugins {
        id("com.android.library") version "8.0.2" apply false
        id("com.google.dagger.hilt.android") version "2.48" apply false
        id("com.google.devtools.ksp") version "1.9.0-1.0.13" apply false 
}

Add this plugins id to your app build.gradle.kts file

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

Okay perfect now , we have completed our dependency step.

We will head to implementation step.

2. Initialize Hilt in the Application Class Annotate your Application class with @HiltAndroidApp

@HiltAndroidApp
class WeatherApplication : Application()

3.Create a Network Module Define a Hilt module to provide dependencies like Retrofit and OkHttpClient.

import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {

    @Provides
    @Singleton
    fun provideRetrofit(): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://api.weatherapi.com/v1/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Provides
    @Singleton
    fun provideWeatherApi(retrofit: Retrofit): WeatherApi {
        return retrofit.create(WeatherApi::class.java)
    }
}

4. Create an API Interface Define an interface for the API endpoints.

import retrofit2.http.GET
import retrofit2.http.Query

interface WeatherApi {
    @GET("forecast.json")
    suspend fun getCurrentWeather(
        @Query("key") apiKey: String,
        @Query("q") location: String,
        @Query("days") days: Int,
        @Query("aqi") aqi: String,
        @Query("alerts") alerts: String
    ): WeatherResponse
}

5. Create a Repository Use the WeatherApi in a repository class. Mark the class with @Inject to enable dependency injection.

import javax.inject.Inject

class WeatherRepository @Inject constructor(private val api: WeatherApi) {

    suspend fun fetchWeather(location: String): WeatherResponse {
        return api.getCurrentWeather("your-api-key", location, 7, "yes", "yes")
    }
}

6. Create a ViewModel Use the repository in your ViewModel. Annotate the ViewModel with @HiltViewModel.

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WeatherViewModel @Inject constructor(
    private val repository: WeatherRepository
) : ViewModel() {

    private val _weatherData = MutableLiveData<WeatherResponse>()
    val weatherData: LiveData<WeatherResponse> get() = _weatherData

    fun loadWeather(location: String) {
        viewModelScope.launch {
            try {
                val weather = repository.fetchWeather(location)
                _weatherData.value = weather
            } catch (e: Exception) {
                // Handle error
            }
        }
    }
}

7. Inject Dependencies in an Activity or Fragment Use the @AndroidEntryPoint annotation to enable dependency injection in your activity or fragment.

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.test.databinding.ActivityMainBinding
import com.example.test.di.WeatherViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class WeatherActivity : AppCompatActivity() {

    private val viewModel: WeatherViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_weather)

        viewModel.weatherData.observe(this) { weather ->
            // Update UI with weather data
        }

        // Fetch weather for a location
        viewModel.loadWeather("New York")
    }
}

Remember one thing that WeatherResponse is your data class and that could a lot longer so i've mentioned here.

Reasons:
  • Blacklisted phrase (1): this plugin
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @Inject
  • User mentioned (0): @AndroidEntryPoint
  • Low reputation (1):
Posted by: Benjamin Lawson