Search code examples
android-studioandroid-roomandroid-livedatakotlin-coroutinesandroid-viewmodel

lateinit property mUserViewModel has not been initialized


I´m trying to read my database, therefore i have created an editext where I will enter a username and a button that allows me to search for the user, but I am presenting an the error in class ListFragment : Fragment(), which says lateinit property mUserViewModel has not been initialized,please help me :(.

//Entity

@Entity(tableName = "user_table")
data class User(
    @PrimaryKey(autoGenerate = true)
    val id: Int,
    val firstName: String,
    val lastName: String,
    val age: Int
)

//Dao

@Dao
interface UserDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun addUser(user: User)
    @Query("SELECT * FROM user_table where firstName LIKE :search LIMIT 1")
    suspend fun readAllData(search : String) : User

}

//UserRepository

class UserRepository(private val userDao: UserDao) {
    suspend fun readAllData(user: String):User{
       return userDao.readAllData(user)
    }
}

//UserViewModel

class UserViewModel(application: Application): AndroidViewModel(application) {
    
   private lateinit var repository:UserRepository
    
    fun search( search : String):User{
        viewModelScope.launch {
            repository.readAllData(search)
        }
  
        return search(String())
    }

}

}

//class

class ListFragment : Fragment() {
    //erro(lateinit property mUserViewModel has not been initialized)
                lateinit var mUserViewModel:UserViewModel
                override fun onCreateView(
                    inflater: LayoutInflater, container: ViewGroup?,
                    savedInstanceState: Bundle?
                ): View? {
                    // Inflate the layout for this fragment
                    val view = inflater.inflate(R.layout.fragment_list, container, false)
            
                    val name = view.editTextTextNameee.text.toString()
                   val prueba = mUserViewModel.search(name)
            
                    if (prueba!=null){
            
                        textView1.text = prueba.firstName
                        textView2.text = prueba.lastName
                        textView3.text = prueba.age.toString()
                    }else {
                        Toast.makeText(context, " Unregistered use", Toast.LENGTH_SHORT).show()
                    }
            
            
                    view.floatingActionButton.setOnClickListener {
                        findNavController().navigate(R.id.action_listFragment_to_addFragment)
                    }
            
                    return view
                }
            }

Solution

  • The reason for the lateinit not initialized property is you haven't created the ViewModel instance. can u try this

    viewModel = ViewModelProvider(requireParentFragment(), factory).get(UserViewModel::class.java)
    

    // factory will be the instance of the View Model

    you can observe the livedata changes the onviewCreated()