【问题标题】:I can't insert data one table to another table in room我无法将数据一张表插入房间的另一张表
【发布时间】:2021-02-18 05:43:21
【问题描述】:

在我的应用程序的房间数据库中,我有一个名为movie_table 的表。当用户单击该项目时,它会保存到另一个名为favorite_table 的表中。我尝试了将近两天,但我无法解决它。我是 MVVM 的新手。 为了更好地理解,请查看代码:

FavoriteMovieDao.kt

    
    @Dao
    interface FavoriteMovieDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertFavMovie(favorite: Favorite)

    @Query("SELECT * FROM favorite_table WHERE id LIKE :id")
    suspend fun getFavoriteMovieById(id:Int): Favorite

    @Query("SELECT * FROM favorite_table")
    suspend fun getAllFavoriteMovie(): List<Favorite>

    @Delete
    suspend fun deleteFavorite(favorite: Favorite)
    }

Repository.kt

    class Repository(context: Context) {
        private val favoriteMovieDao: FavoriteMovieDao = MovieDatabase.invoke(context).getFavoriteMovieDao()
    suspend fun insertFavMovie(favorite: Favorite){
        favoriteMovieDao.insertFavMovie(favorite)
    }

MovieDetailsViewModel.kt

    class MovieDetailsViewModel(private val repository: Repository):ViewModel() {
        private val favMovieResponse:MutableLiveData<List<Favorite>> = MutableLiveData()
        val actorResponse:MutableLiveData<List<Movie>> = MutableLiveData()
        private val insertFavMovie:MutableLiveData<Favorite> = MutableLiveData()

        fun actorDetail(){
            viewModelScope.launch {
                val actor = repository.getAllMovieDB()
                actorResponse.value = actor
            }
        }

        fun insertFavMovie(favorite: Favorite){
            viewModelScope.launch {
                //i can't insert this
                val insertFav = repository.insertFavMovie(favorite)
                insertFavMovie.value = insertFav
            }
        }
    }
 }

MovieDetailsActivity.kt

class MovieDetailsActivity : AppCompatActivity(){

private lateinit var actorViewModel: MovieDeatilsViewModel
private val actorAdapter by lazy { ActorAdapter() }
private var isFav: Boolean = false


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


    val repository = Repository(this)
    val viewModelFactory = MovieDetailsViewModelFactory(repository)
    actorViewModel = ViewModelProvider(this,viewModelFactory).get(MovieDeatilsViewModel::class.java)

    setUpPostRecyclerView()
    actorViewModel.actorDetail()
    actorViewModel.actorResponse.observe(this, Observer {actorList ->
        actorAdapter.setData(actorList)
    })

    initBundle()
    
    favBtn.setOnClickListener {
        if (isFav){
            isFav = false
            favBtn.supportImageTintList = ColorStateList.valueOf(Color.parseColor("#E4C1C1"))

            Log.d("msg","Not Favorite!")
        }else{
            isFav = true
            favBtn.supportImageTintList = ColorStateList.valueOf(Color.parseColor("#FFC107"))
            Log.d("msg","Favorite!")
        }
    }

}

private fun initBundle() {
    val bundle:Bundle? = intent.extras
    movieTitle.text = bundle!!.getString("title")
    directorbc.text = bundle.getString("director")
    genre.text = bundle.getString("genre")
    releaseYear.text = bundle.getInt("year").toString()
    language.text = bundle.getString("language")
    country.text = bundle.getString("country")
    rating.text = bundle.getString("rating")
    plotText.text = bundle.getString("plot")
    //moviePosterD.setImageDrawable(bundle!!.getString("image"))
    Glide.with(this).load(bundle.getString("image")).into(moviePosterD);

    val player = SimpleExoPlayer.Builder(this).build()
    player.preparePlayer(movieView)
    player.setSource(applicationContext, "http://html5videoformatconverter.com/data/images/happyfit2.mp4")

}

private fun setUpPostRecyclerView(){
    actorRecyclerview.adapter = actorAdapter
    actorRecyclerview.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
}

}

如何插入?请帮我。谢谢

【问题讨论】:

  • 您能否详细说明您的click 功能实现?
  • @theThapa 我更新了我的问题,现在你可以看到点击功能了。谢谢
  • 您似乎错过了在单击FAB 按钮时调用 ViewModel 的 fun insertFavMovie(favorite: Favorite){ .. } 函数。

标签: android database android-studio kotlin android-room


【解决方案1】:

在电影表中,要处理最喜欢的电影,您可以在每个电影项目中使用一个变量,例如可以将其设置为 true 或 false。这允许您使用过滤器进行查询以在屏幕上显示它们。我认为您不需要另一张桌子来存储收藏夹。我希望这会有所帮助!如果您在此处分享更多详细信息,我可以帮助您进行设计。

@Entity
data class Movie( val title: String, val isFavourite: Boolean = false)

更新 1:

当用户点击favButton 时,MovieViewModel 中的 Movie 实体更新如下:

fun setMovie(movie: Movie){
        _movie.value = movie
    }
fun updateMovie(movie: Movie) {
        movie.isFavourite = !movie.isFavourite
        viewModelScope.launch {
            repository.updateMovie(movie)
            setMovie(movie)
        }
    }

MovieDao

@Update
suspend fun updateMovie(movie: Movie)

更新 2: 在MoviesDao

 @Update
    suspend fun updateMovie(movie: Movie)

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertAll(vararg movie: Movie)

    @Query("select * from movies_table where isFavourite = 1")
    fun getFavMovies(): LiveData<List<Movie>>

    @Query("Select * from movies_table")
    fun getAllMovies(): LiveData<List<Movie>>

在存储库中

val favMovies: LiveData<List<Movie>> = moviesDao.getFavMovies()

更新 3:

 favBtn.setOnClickListener {
            _viewModel.updateMovie(movie)
        }

_viewModel.movie.observe(viewLifecycleOwner, Observer {
            //Update UI based on isFavourite value on Movie
        })

【讨论】:

  • 我认为您的想法,我可以产生一个想法,但这次无法实施。我已经在您的电子邮件中向您发送了更多详细信息。请检查您的电子邮件并帮助我。谢谢
  • 具体哪一部分看不懂?看,你有一个 Movies 表,所有电影都存储在这个表中,每个 Movie 实体都有一个布尔值 isFavourite,最初设置为 false。当单击电影以添加到收藏夹时,isFavourite 设置为 true。您可以通过检查此变量来检索所有电影或 favouriteMovies,当您要从收藏夹中删除电影时,再次将 isFavourite 重置为 false。
  • 谢谢,我正在创建这个 dao `@Query("SELECT * FROM movie_table WHERE isFavorite LIKE :isFav") suspend fun getFavoriteMovie(isFav: Boolean)` 是否正确?
  • 查询将是`@Query("select * from movie_table where isFavourite = 1") fun getFavouriteMovies(): LiveData>`
  • 好的,这对我有帮助,但我想知道用户可以单击 favButton 然后它被选择为最喜欢的电影。我该怎么做。实际上我想知道用户可以选择他们最喜欢的电影一个然后所有最喜欢的电影节目都在回收站视图中。我该怎么做?
猜你喜欢
  • 2023-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-09
  • 1970-01-01
  • 2019-10-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多