Android Room LiveData观察器未更新

问题描述 投票:1回答:1

我有一个带有FragmentRecyclerView。我使用ViewModel来保存LiveData从Room数据库中显示,并尝试通过观察RecyclerView中的数据来更新ViewModel。但是当我打开片段时,Observer只会被调用一次。我从不同于Fragment打开的Observer更新Room数据库。

我添加了一个新的Event或删除或更新了它,但Observer从未被调用!我如何才能正确调用Observer?我的错误在哪里?

片段

onViewCreated中的代码在onCreate中不起作用,它在val recyclerview = upcoming_recycler行上返回null。您还可以在onViewCreated的末尾看到我打开的新片段,从该片段中更新数据库。请注意,UpcomingFragmentFragmentLayout位于不同的EventEditFragment

class UpcomingFragment : Fragment(R.layout.fragment_upcoming) {

    private val clubDb by lazy {
        ClubDatabase.getClubDatabase(requireContext().applicationContext)
    }

    private val eventAdapter = EventAdapter(null, this)

    private val upcomingViewModel: UpcomingViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val recyclerView = upcoming_recycler
        recyclerView.layoutManager = LinearLayoutManager(context)
        recyclerView.setHasFixedSize(true)

        upcomingViewModel.eventsToShow.observe(viewLifecycleOwner, Observer { events ->
            Log.d(TAG, "Live data changed in upcomingfragment!!!")
            eventAdapter.setData(events.toTypedArray())
        })

        recyclerView.adapter = eventAdapter

        // add a new Event
        upcoming_fab.setOnClickListener {
            parentFragmentManager.beginTransaction()
                .replace(R.id.main_fragment_layout_overlay, EventEditFragment())
                .addToBackStack(EVENT_EDIT_FRAGMENT)
                .commit()
        }
        // and more stuff...
    }
    //the rest of the class
}

ViewModel

class UpcomingViewModel(application: Application) : ViewModel() {
    val eventsToShow: LiveData<List<Event>>

    init {
        val roundToDay = SimpleDateFormat("dd.MM.yyy", Locale.GERMAN)
        var today = Date()
        today = roundToDay.parse(roundToDay.format(today))!!
        val tomorrow = Date(today.time + 86400000L)
        eventsToShow = ClubDatabase.getClubDatabase(application.applicationContext).clubDao()
            .getEventsByClubIdAfterDate(CURRENT_CLUB_ID, tomorrow)
    }
}

EventAdapter

class EventAdapter(
    private var dataSet: Array<Event>?,
    private val onEventItemClickListener: OnEventItemClickListener
) : RecyclerView.Adapter<EventAdapter.EventViewHolder>() {

    class EventViewHolder(val view: View) : RecyclerView.ViewHolder(view)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EventViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.event_item_layout, parent, false)
        return EventViewHolder(view)
    }

    override fun onBindViewHolder(holder: EventViewHolder, position: Int) {
        // show the item & add onEventItemClickListener for updating
    }

    fun setData(new: Array<Event>) {
        this.dataSet = new
        this.notifyDataSetChanged()
    }

    override fun getItemCount(): Int {
        return dataSet?.size ?: 0
    }
}

数据库

@Database(
entities = [Event::class, Member::class, RequiredMembersForEvents::class, AttendedMembersForEvents::class],
version = 9,
exportSchema = false
)
@TypeConverters(Converters::class)
abstract class ClubDatabase : RoomDatabase() {
    abstract fun clubDao(): ClubDao

    companion object {
        @Volatile
        private var INSTANCE: ClubDatabase? = null

        fun getClubDatabase(context: Context): ClubDatabase {
            return INSTANCE ?: synchronized(this) {
                val instance = INSTANCE
                return if (instance != null) {
                    instance
                } else {
                    Room.databaseBuilder(
                        context.applicationContext,
                        ClubDatabase::class.java,
                        "club-db"
                    )
                        .allowMainThreadQueries()
                        .fallbackToDestructiveMigration()
                        .build()
                }
            }
        }
    }
}

DAO

@Dao
interface ClubDao {

    @Query("SELECT * FROM events WHERE clubId = :clubId AND dateTimeFrom > :date ORDER BY dateTimeFrom ASC")
    fun getEventsByClubIdAfterDate(clubId: String, date: Date): LiveData<List<Event>>

    // the rest of the DAO
}
android android-fragments android-room viewmodel android-livedata
1个回答
0
投票

检查您的数据库单例实现,因为那里的INSTANCE变量-始终为null。在拥有该类的实例时,应该在第一次设置它。否则,您的应用程序将处理数据库类的不同实例。

[虽然对数据库进行了一些更改,但未触发LiveData的这些更改的观察者,但可能会引起问题。

© www.soinside.com 2019 - 2024. All rights reserved.