You are currently viewing First time using Kotlin, issues with Room and coroutines, assistance appreciated for basic error

First time using Kotlin, issues with Room and coroutines, assistance appreciated for basic error

Please feel free to let me know if this would be more appropriate to post elsewhere.

I’m trying to return the results of an sqlite query created in my dao that requires a string input, but the result is returning ‘kotlin.unit’ instead of the expected query results. I’ve created this by following a couple different tutorials but I’m obviously missing some fundamentals.

Database

@Database(entities = [User::class], version = 1, exportSchema = false) abstract class UserDatabase: RoomDatabase() { abstract fun userDao(): UserDao companion object{ @Volatile private var INSTANCE: UserDatabase? = null fun getDatabase(context: Context): UserDatabase{ val tempInstance = INSTANCE if(tempInstance != null){ return tempInstance } synchronized(this){ val instance = Room.databaseBuilder( context.applicationContext, UserDatabase::class.java, "user_database" ).build() INSTANCE = instance return instance } } } } 

Entity

@Entity(tableName = "user_table") data class User( val username: String ) 

Dao

interface UserDao { @Query("SELECT * FROM user_table WHERE username LIKE :userName") fun getUsername(userName: String): User } 

Repository

class UserRepository(private val userDao: UserDao) { fun getUsername(userName: String):User{ return userDao.getUsername(userName) } } 

View Model

class UserViewModel(application: Application): AndroidViewModel(application) { private val repository: UserRepository init { val userDao = UserDatabase.getDatabase(application).userDao() repository = UserRepository(userDao) } fun getUsername(userName: String) { viewModelScope.launch(Dispatchers.IO) { repository.getUsername(userName) } } } 

Login Fragment

class LoginFragment : Fragment(R.layout.fragment_login) { private lateinit var mUserViewModel: UserViewModel private val uiScope = CoroutineScope(Dispatchers.Main) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mUserViewModel = ViewModelProvider(this).get(UserViewModel::class.java) button_sign_in.setOnClickListener{ loginButton() } } fun loginButton(){ val username = edittext_username.text.toString() uiScope.launch{ val user = mUserViewModel.getUsername(username) Toast.makeText(requireContext(), user.toString(), Toast.LENGTH_LONG).show() } } } 

In my login fragment, I click the ‘button_sign_in’ button and expect the app to return query results based on the text in the ‘edittext_username’ field, but instead the toast message just says ‘Kotlin.Unit’. Unfortunately I’ve become quite confused when it comes to passing data between Room classes, any advice would be appreciated.

submitted by /u/TheBuffaloMan117
[link] [comments]