sqlite 将Fviorites项目保存到聊天室数据库时出现问题,已保存重复项目,无法检查是否也已保存

svdrlsy4  于 2022-11-15  发布在  SQLite
关注(0)|答案(1)|浏览(231)

当我更新我的应用程序的某些部分时,我认为我做了一些错误的事情或缺少了什么,导致了这个问题,当我试图将任何项目保存到收藏夹表时,问题发生了,在我保存它后,我打开了相同的项目(再次打开片段详细信息),我应该看到收藏图标**(心形图标)**充满了红色,这意味着该项目已经保存,如果我再次点击它,它应该被删除,依此类推……
现在我看到该项目已保存,但当我单击Back按钮并再次单击该项目时,图标不会改变,这意味着用户可以再次保存它(这会导致RececumerView中出现重复的项目)

GIF中的问题

这是我的代码

FavoritesEntity类

@Parcelize
@Entity(tableName = "favorites")
data class FavoritesEntity(@PrimaryKey(autoGenerate = true) val id: Int, val item: Item) : Parcelable

数据库类

@Database(
    entities = [Item::class, FavoritesEntity::class],
    version = 1,
    exportSchema = false
) //@TypeConverters(Converters.class)

//@TypeConverters(Converters.class)
//@TypeConverters(Converters.class)
@TypeConverters(ItemTypeConverter::class)
abstract class ItemsDatabase : RoomDatabase() {

    //    private static ItemsDatabase INSTANCE;
    abstract val itemDAO: ItemDAO
    
    companion object {

        @Volatile
        private var INSTANCE: ItemsDatabase? = null

        @Synchronized
        fun getInstance(context: Context): ItemsDatabase {

            if (INSTANCE == null) {

                INSTANCE = Room.databaseBuilder(
                    context.applicationContext,
                    ItemsDatabase::class.java,
                    "items_database"
                ).fallbackToDestructiveMigration()
                    .build()

                return INSTANCE!!
            }
            return INSTANCE as ItemsDatabase
        }
    }
}

ItemDAO

@Dao
interface ItemDAO {
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertItem(item: Item)

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertFavorites(favoritesEntity: FavoritesEntity)

    @get:Query("SELECT * FROM FAVORITES")
    val getAllFavorites: Flow<List<FavoritesEntity>>

    @Delete
    suspend fun deleteFavorite(favoritesEntity: FavoritesEntity)

    @Query("DELETE FROM FAVORITES")
    suspend fun deleteAllFavorites()

    @Query("SELECT * FROM item_table order by datetime(published) DESC")
    fun getAlItems(): Flow<List<Item>>

    @Query("SELECT * FROM item_table WHERE title like '%' || :keyword || '%' ")
    suspend fun getItemsBySearch(keyword: String?): List<Item>
}

DetailsViewModel

@HiltViewModel
class DetailsViewModel @Inject constructor(
    private val mainRepository: MainRepository,
    private val dataStoreRepository: DataStoreRepository
) : ViewModel() {

    private val _favoritesPostList = MutableLiveData<List<FavoritesEntity>>()
    val favoritesPostList: LiveData<List<FavoritesEntity>> get() = _favoritesPostList

    fun getFavoritePosts() {
        viewModelScope.launch {
            mainRepository.localDataSource.getAllFavorites().collect {
                _favoritesPostList.value = it
            }
        }
    }

    val readRecyclerViewPortraitLayout =
        dataStoreRepository.readRecyclerViewPortraitLayout.asLiveData()
    val readRecyclerViewLandscapeLayout =
        dataStoreRepository.readRecyclerViewLandscpaeLayout.asLiveData()

    fun saveRecyclerViewPortraitLayout(layout: String) {
        viewModelScope.launch {
            dataStoreRepository.saveRecyclerViewPortraitLayout(layout)
        }
    }

    fun saveRecyclerViewLandscapeLayout(layout: String) {
        viewModelScope.launch {
            dataStoreRepository.saveRecyclerViewLandscapeLayout(layout)
        }
    }

    fun insertFavorites(favoritesEntity: FavoritesEntity) {
        viewModelScope.launch(Dispatchers.Default) {
            mainRepository.localDataSource.insertFavorites(favoritesEntity)
        }
    }

    fun deleteFavoritePost(favoritesEntity: FavoritesEntity) {
        viewModelScope.launch(Dispatchers.IO) {
            mainRepository.localDataSource.deleteFavorite(favoritesEntity)
        }
    }

    fun deleteAllFavorites() {
        viewModelScope.launch(Dispatchers.IO) {
            mainRepository.localDataSource.deleteAllFavorites()
        }
    }
}

细节活跃度

@AndroidEntryPoint
class DetailsActivity : AppCompatActivity() {
    private var _binding: ActivityDetailsBinding? = null
    private val binding get() = _binding!!
    private var url: String? = null
    private var title: String? = null
    private var content: String? = null
    private var youtubeThumbnailImageSrc: String? = null
    private var youTubeLink: String? = null
    private var youtubeThumbnailImageSetVisibility: Int? = null

    private var html: Spannable? = null

    private val detailsViewModel: DetailsViewModel by viewModels()

    private var postItem: Item? = null

    private var postFavoritesSaved = false
    private var postFavoritesSavedId = 0
    private var menuItem: MenuItem? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityDetailsBinding.inflate(layoutInflater)
        setContentView(binding.root)
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        supportActionBar?.setDisplayShowHomeEnabled(true)
        binding.progressBar.visibility = View.VISIBLE
        Log.d(
            TAG,
            "onCreate checkSavedFavoritesItems: $postFavoritesSavedId"
        )

        postItem = if (intent.extras!!.containsKey("postItem")) {
            intent.getParcelableExtra("postItem")!!
        } else {
            val favoriteItem: FavoritesEntity = intent.getParcelableExtra("favoriteItem")!!
            favoriteItem.item
        }
  
    }

    override fun onDestroy() {
        super.onDestroy()

        changeMenuItemIcon(menuItem, R.drawable.ic_favorite_border)
        binding.fab.setOnClickListener(null)
        adRequest = null
        _binding = null
    }

    private fun changeMenuItemIcon(menuItem: MenuItem?, icFavoriteBorder: Int) {
        menuItem?.setIcon(icFavoriteBorder)
    }

        private fun checkSavedFavoritesItems(menuItem: MenuItem?) {
        detailsViewModel.favoritesPostList.observe(this) { favoritesEntity ->
            try {
                
                favoritesEntity.forEach {
                    if (it.item.id == postItem?.id) {
                        changeMenuItemIcon(menuItem, R.drawable.ic_favorite)
                        postFavoritesSavedId = it.id
                        Log.d(TAG, "checkSavedFavoritesItems: $postFavoritesSavedId")
                        postFavoritesSaved = true
                    }
                }
                
            } catch (exception: Exception) {
                Log.e(TAG, "checkSavedFavoritesItems: " + exception.message)
            }
        }
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.details_menu, menu)
        menuItem = menu.findItem(R.id.action_add_to_favorites)
        checkSavedFavoritesItems(menuItem)
        return true
    }

    override fun onOptionsItemSelected(menuItem: MenuItem): Boolean {
        when {
            menuItem.itemId == R.id.action_add_to_favorites && !postFavoritesSaved -> {
                saveTogFavorites(menuItem)
            }
            menuItem.itemId == R.id.action_add_to_favorites && postFavoritesSaved -> {
                removePostFromFavorites(menuItem)
            }

            menuItem.itemId == android.R.id.home -> this.finish()
        }
        return super.onOptionsItemSelected(menuItem)
    }

    private fun saveTogFavorites(menuItem: MenuItem) {
        val favoritesEntity = postItem?.let {
            FavoritesEntity(0, it)
        }
        if (favoritesEntity != null) {
            detailsViewModel.insertFavorites(favoritesEntity)
        }
        menuItem.setIcon(R.drawable.ic_favorite)
        Snackbar.make(binding.root, "Saved", Snackbar.LENGTH_LONG).show()
        postFavoritesSaved = true
    }

    private fun removePostFromFavorites(menuItem: MenuItem) {
        val favoritesEntity = postItem?.let { FavoritesEntity(postFavoritesSavedId, it) }
        Log.d(
            TAG, "checkSavedFavoritesItems: $postFavoritesSavedId"
        )
        if (favoritesEntity != null) {
            detailsViewModel.deleteFavoritePost(favoritesEntity)
        }
        menuItem.setIcon(R.drawable.ic_favorite_border)
        Snackbar.make(
            binding.root,
            "Post deleted from favorites", Snackbar.LENGTH_LONG
        ).show()
        postFavoritesSaved = false
    }

我尝试在日志中检查postFavoritesSavedId,但每次都得到0,所以我尝试将其更改为获取项目本身的长ID,而不是FavoritesEntity增量ID,但不起作用

wlzqhblo

wlzqhblo1#

在此方法中,您在favoritesEntity中观察到了checkSavedFavoritesItems,但您忘记了调用getFavoritePosts方法,因为发生了此问题

相关问题