35

I have a class which i inject into a ViewModel + ViewModel factory, when initialise the view model in the onCreate method in activity, its says the value being passed through is not initialised.

Below is my code

I am quite new to Kotlin so have tried debugging but am stuck on this issue.

Here is MainActivity code:

class MainActivity: AppCompatActivity(), RepoSelectedListener {


    @Inject
    lateinit var viewModel: MainActivityListViewModel

    lateinit var lifecycleOwner: LifecycleOwner
    lateinit var repoSelectedListener: RepoSelectedListener

    @Inject
    lateinit var repository: RepoRepository


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

        viewModel = ViewModelProviders.of(this, ViewModelFactory(repository)).get(MainActivityListViewModel::class.java)

        repoRecyclerView.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = RepoListAdapter(viewModel, lifecycleOwner, repoSelectedListener)
        }


**My ViewModel:**



   class MainActivityListViewModel @Inject constructor(val 
    repoRepository: RepoRepository): BaseViewModel() {

    //private lateinit var repoRepository: RepoRepository
    private var disposable: CompositeDisposable? = null

    private val repos = MutableLiveData<List<Repo>>()
    private val repoLoadError = MutableLiveData<Boolean>()
    private val loading = MutableLiveData<Boolean>()


     init {
        disposable = CompositeDisposable()
        fetchRepos()
      }

     fun getRepos(): LiveData<List<Repo>> {
        return repos
     }
    }

my ViewModelFactory:

   class ViewModelFactory @Inject constructor(private val 
   repoRepository: RepoRepository): ViewModelProvider.Factory{


    override fun <T : ViewModel?> create(modelClass: Class<T>): T {
        if 
   (modelClass.isAssignableFrom(MainActivityListViewModel::class.java)) 
   {
            @Suppress("UNCHECKED_CAST")
            return MainActivityListViewModel(this.repoRepository) as T
        }
        throw IllegalArgumentException("Unknown ViewModel class")

    }


   }

my Class Repo:

  class RepoRepository @Inject constructor(private val githubRepos: 
    GithubRepos){


    private lateinit var repoService: GithubRepos


    fun getRepositories(): Single<List<Repo>> {
        return repoService.getRepos()
    }

    fun getSingleRepo(owner: String, name: String): Single<Repo> {
        return repoService.getSingleRepo(owner, name)
    }
   }

This is error i receive:

   Unable to start activity ComponentInfo{com.carllewis14.repos/com.carllewis14.repos.ui.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property 
  repository has not been initialized
9
  • you are accessing variable(repository) which must exist, but it is not initialized at a time, make it optional or initialize it before usage Jul 24, 2019 at 12:19
  • You should inject your RepoRepository to your activity. Or inject MainActivityListViewModel and access your repo from viewmodel. Jul 24, 2019 at 12:22
  • @AlexandrKolesnik how do i initialize before usage is what i am asking
    – DanYon
    Jul 24, 2019 at 12:26
  • @EnsarBayhan the MainActivityListViewModel is injected already
    – DanYon
    Jul 24, 2019 at 12:27
  • @DanYon Yo have to inject to your MainActivity. Jul 24, 2019 at 12:29

4 Answers 4

56

This is because you are trying to use the repository before initializing it with an instance without checking its initialization.

When using lateinit nullity cannot be used in that variable.

lateinit var repository: RepoRepository

Then, before using any method of the object, check that it is initialized:

if (::repository.isInitialized) {}

GL

2
  • 3
    lateinit is not allowed on nullable types Jan 3, 2020 at 15:39
  • 1
    Then the isInitialized is like a null check. Why not using a nullable property for these cases?
    – JCarlosR
    Feb 7, 2022 at 15:00
6

if you're using Kotlin 1.2, you can easily check whether a lateinit variable has been initialized or not. If not, well, you can always use the not null approach.

Anyways, here's how you can check if a lateinit var has been initialized or not:

if (::fullName.isInitialized) {
    print("Hi, $fullName")
}
4

have a look at my answer here (maybe it helps ) Nullable var with `?` vs. lateinit var

Essentially, you are never initializing your repository: RepoRepository.

From the code you have written, you won't need an instance of your repository in your activity as well, it should just be created in the constructor of your ViewModel (which has injection)

You are also going to have a similar issue with private lateinit var repoService: GithubRepos; if it's in the constructor of your object, you don't have to declare it again.

2
  • just to clarify i wont need to inject repository: RepoRepository, in my activity because its injected into my viewmodel? so i should just have the viewmodel creation as viewModel = ViewModelProviders.of(this).get(MainActivityListViewModel::class.java) ? As if i include my viewmodelfactory like :` viewModel = ViewModelProviders.of(this, ViewModelFactory(repository)).get(MainActivityListViewModel::class.java)` then i have to add the instance as it appears in my viewmodel factory constructor
    – DanYon
    Jul 24, 2019 at 14:55
  • ok let me try that and get back to you @a_local_nobody i appreciate the help
    – DanYon
    Jul 24, 2019 at 16:17
0

it seems the question code is shadowing the injection FYI you can also initialize by lazy :

To create an object that will be initialized at the first access to it, we can use the lazy method:

val lazyValue: ClassWithHeavyInitialization by lazy {
        numberOfInitializations.incrementAndGet()
        ClassWithHeavyInitialization()
    }

https://www.baeldung.com/kotlin-lazy-initialization also see kotlin docs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.