Home > Back-end >  How to Use Hilt in Launch Screen Activity Kotlin
How to Use Hilt in Launch Screen Activity Kotlin

Time:08-18

Cannot create instance of viewmodel in launchscreen activity

This is the Manifest file

<application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:icon="@drawable/pasumai"
    android:label="@string/app_name"
    android:roundIcon="@drawable/pasumai"
    android:supportsRtl="true"
    android:theme="@style/Theme.PasumaiSuperMarket"
    android:usesCleartextTraffic="true"
    tools:node="replace">

<activity
        android:name=".activity.launchscreen"
        android:exported="true"
        android:theme="@style/splashscreentheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

I am also adding @AndroidEntryPoint in launchscreen activity

This is the ViewModel Code

@HiltViewModel

class LoginVM @Inject constructor(val repository: NewApiRepository, val useridrepository:ImplRepository, @ApplicationContext val context: Context) : ViewModel() {

val myOtp: MutableStateFlow<Resource<LoginOtp>> = MutableStateFlow(Resource.Empty)
val myLogin: MutableStateFlow<Resource<OtpVerification>> = MutableStateFlow(Resource.Empty)
var user_id : MutableLiveData<String> = MutableLiveData("")
var userid: MutableLiveData<userid> = MutableLiveData()

fun saveuserid(user:String) {
   viewModelScope.launch(Dispatchers.IO) {
       useridrepository.saveuser(
           userid(id = user)
       )
   }
}

fun retrieveUserId() {
   viewModelScope.launch(Dispatchers.IO) {
       useridrepository.getuser().collect{
           user_id.postValue(it.id)
       }
   }
}

fun getOtp(mobile:String) = viewModelScope.launch(Dispatchers.IO) {
    myOtp.value = Resource.Loading
    myOtp.value = repository.getotp(90336,"send-sms", mobile)
}

fun login(mobile:String,otp:String,friends_code:String) = viewModelScope.launch(Dispatchers.IO) {
    myLogin.value = Resource.Loading
    myLogin.value = repository.loginuser(90336,"user-login", mobile,otp,friends_code)
}

}

This is Activity Code

@AndroidEntryPoint

class launchscreen : AppCompatActivity() {

private val otpvm by viewModels<LoginVM>()

override fun onCreate(savedInstanceState: Bundle?) {

    super.onCreate(savedInstanceState)

    setContentView(R.layout.activity_launchscreen)

    otpvm.retrieveUserId()

    lifecycleScope.launchWhenStarted {
        otpvm.user_id.observe(this@launchscreen) {
            if(it.isNullOrEmpty()) {
                navToSignUpActivity()
            } else {
                Utils.User_id = it
                navToMainActivity()
            }
        }
    }
}

}

CodePudding user response:

hey you need to add following dependency.

implementation "androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03"

and now in LaunchScreenActivity, you need to make following things

@AndroidEntryPoint
class LaunchScreenActivity:AppCompatActivity(){
   private val viewModel by viewModels<LaunchScreenViewModel>()
}

and your LaunchScreenViewModel should be as following:

@HiltViewModel
class LaunchScreenViewModel @Inject constructor(
   /*some constructor injections*/
) : ViewModel(){
   
}

If you got the answer you want please accept my answer by giving green check. If I haven't got your question then give me more details in comment section of this answer. Love from India.❤️

CodePudding user response:

You need to make sure that you have are providing your repositories as follows (doesnt have to be SingletonComponent depends on your use case) :

@Module
@InstallIn(SingletonComponent::class)
abstract class CoreRepositoryModule {
     @Binds
     abstract fun bindNewApiRepository(
         newApiRepository: NewApiRepositoryImpl
     ): NewApiRepository
    
     @Binds
     abstract fun bindUserIdRepository(
         userIdRepository: ImplRepository
     ): UserIdRepository
}

Also, I don't see your application class with @HiltAndroidApp annotation so make sure you have the following :

@HiltAndroidApp
class MyApplication : Application()

Then you can just do:

@AndroidEntryPoint
class MainActivity : AppCompatActivity(R.layout.main_activity) {
    private val viewModel: LaunchScreenViewModel by viewModels()
}

and for viewModel:

@HiltViewModel
class MainViewModel @Inject constructor(
   .....
) : ViewModel()

further more the reason you might be getting the has no zero argument constructor error it means that the HiltViewModelFactory doesn't have a binding for your specific viewmodel. you might be missing hilt-android-compiler so please use the following in app level gradle (use apply plugin: 'kotlin-kapt' for kapt on top) :

// Dependency Injection
    implementation "com.google.dagger:hilt-android:2.41"
    kapt "com.google.dagger:hilt-android-compiler:2.40.5"
    kapt 'androidx.hilt:hilt-compiler:1.0.0'
    implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'
    implementation 'androidx.hilt:hilt-work:1.0.0'
  • Related