簡體   English   中英

使用 Hilt 和房間數據庫的依賴注入

[英]Dependency injection with Hilt and room database

所以我目前正試圖弄清楚如何實現一個名為 UserViewModel 的 class,它使用帶柄的 di 到一個包含按鈕的組合中。 單擊此按鈕時,將獲取用戶信息,例如姓名和電子郵件,並使用房間將其保存到數據庫中。 到目前為止,我已經將所有內容都提升為一個“單一”可組合 - UserProfileState。

我怎樣才能做到這一點,當用戶單擊“保存信息”時,UserViewModel 將從可組合接收事件並將其保存到數據庫中?

我連接到數據庫的主viewModel class。

@HiltViewModel
class UserViewModel @Inject constructor(
    private val repo: UserRepository
): ViewModel() {

    fun addUser(users: Users) = viewModelScope.launch(Dispatchers.IO) {
            repo.addUser(users)
    }

    fun updateUser(users: Users) = viewModelScope.launch(Dispatchers.IO) {
            repo.updateUser(users)
    }

    fun deleteUser(users: Users) = viewModelScope.launch(Dispatchers.IO) {
            repo.deleteUser(users)
    }

}

我的按鈕:(單擊時,應將用戶信息保存到我已經使用房間創建的數據庫中)

Button(
  colors = ButtonDefaults.buttonColors(backgroundColor = LightBlue),
  modifier = Modifier.size(160.dp, 50.dp),
  onClick = { 
             val userInfo = Users(id, username, email)
                 viewmodel.addUsers(users)
            },

  ) {
      Text(
           text = "Save Info",
           color = Color.White,
           fontWeight = FontWeight.Bold,
           fontSize = 15.sp
            )
    }

My Hoisted 可組合,窗體可組合:

@Composable
fun UserProfileState() {
    val viewModel = viewModel<UserViewModel>() <-- When I added this, the app crashes !!
    var username by rememberSaveable { mutableStateOf("") }
    var email by rememberSaveable { mutableStateOf("") }
//    val userInfoSaved = viewModel.addUser(Users (username, email) )

    UserProfile(
        username = username,
        onUsernameChange = { username = it },
        email = email,
        onEmailChange = { email = it },

        )
    
}

更新:

這是我的屏幕可組合按鈕。

@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun UserProfile(
    username: String,
    onUsernameChange: (String) -> Unit,
    email: String,
    onEmailChange: (String) -> Unit,
    viewModel: UserViewModel,

) {
    val scrollState = rememberScrollState()

    Column(
        modifier = Modifier.fillMaxSize(),
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        Box(
            modifier = Modifier
                .fillMaxSize()

        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .verticalScroll(scrollState), // Allows scroll-ing in profile screen
                verticalArrangement = Arrangement.Top,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {

                ProfilePicture(imageSize = 150.dp)

                // Username
                Spacer(modifier = Modifier.height(20.dp))

                OutlinedTextField(
                    value = username,
                    onValueChange = onUsernameChange,
                    modifier = Modifier
                        .wrapContentSize()
                        .fillMaxWidth(0.944f),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        focusedBorderColor = LightBlue
                    ),
                    label = { Text(text = "Name") },
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Email,
                            contentDescription = "Name"
                        )
                    },

                    )

                // Email
                Spacer(modifier = Modifier.height(10.dp))

                OutlinedTextField(
                    value = email,
                    onValueChange = onEmailChange,
                    modifier = Modifier
                        .wrapContentSize()
                        .fillMaxWidth(0.944f),
                    colors = TextFieldDefaults.outlinedTextFieldColors(
                        focusedBorderColor = LightBlue
                    ),
                    label = { Text(text = "Email") },
                    singleLine = true,
                    leadingIcon = {
                        Icon(
                            imageVector = Icons.Default.Email,
                            contentDescription = null
                        )
                    },

                    )

                Spacer(modifier = Modifier.height(20.dp))
                BaseScreen()

                Spacer(modifier = Modifier.height(50.dp))
                Button(
                    colors = ButtonDefaults.buttonColors(backgroundColor = LightBlue),
                    modifier = Modifier.size(160.dp, 50.dp),
                    onClick = {
                                viewModel.addUser(Users(id = UUID.randomUUID(), username, email))
                              },
                ) {
                    Text(
                        text = "Save Info",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 15.sp
                    )
                }

            }
        }
    }
}

您應該將以下代碼添加到 build.gradle 中的依賴項中:

 implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.5.1"

並在您的活動中創建一個 ViewModel 實例,如下所示:

val userViewModel  = viewModel<UserViewModel >()

- 更新 -

你的 setContent 應該是這樣的:

setContent {
            YourComposeTheme {
                val userViewModel  = viewModel<UserViewModel >()
                var username by rememberSaveable { mutableStateOf("") }
                var email by rememberSaveable { mutableStateOf("") }

                Column(...) {

                //your TextFields ...

                Button(//according your codes
                    colors = ButtonDefaults.buttonColors(backgroundColor = LightBlue),
                    modifier = Modifier.size(160.dp, 50.dp),
                    onClick = {
                        val userInfo = Users(id, username, email)
                        userViewModel.addUsers(userInfo)
                    },

                    ) {
                    Text(
                        text = "Save Info",
                        color = Color.White,
                        fontWeight = FontWeight.Bold,
                        fontSize = 15.sp
                    )
                }
            }
            }
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM