'Why is the database id of the last inserted object always 0?

In the below method, I'm inserting an object into a table and then calling a method to return the id of that object just added; I need its id to place into another cross reference table. Every time I insert the two ids into this cross reference table, however, the gamebook id is always 0, even though when I inspect the gamebooks table in the database inspector, it's clearly being assigned an id by Room (using auto increment). What am I missing or doing wrong?

    @Override
    public void onSaveGamebookClicked(Gamebook gamebook, int collectionId) {

    mainViewModel.insertGamebook(gamebook);
    long id = mainViewModel.getLastId();

    CollectionWithGamebooksEntity collectionWithGamebooksEntity = new CollectionWithGamebooksEntity(collectionId, id);
    mainViewModel.insertCollectionWithGamebooks(collectionWithGamebooksEntity);
 }

Here's the Dao method:

     @Insert
     long insert (Gamebook gamebook);

Here's the Dao method I'm using to get the id of the last gamebook added:

     @Query("SELECT gamebookId FROM gamebooks_table")
     long getLastID();


Solution 1:[1]

For anyone who's experiencing the same problem, I found that my issue was being caused by having the observer in the wrong place. When I moved the observer to my Activity's onCreate() method, and checked to make sure there was something to actually observe (e.g., when the app is run for the first time, there's nothing to observe because nothing has been added to the database), everything worked.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 James Whelan