Search code examples
javaandroidsqlitedao

How do you get a String[] from a Room database?


Pretty self-explanatory. I have a Room database, one of the tables has a column of type String, I want to get all the data in that column and return it as String[]. For some reason, that String[] is always empty. What am I doing wrong?

Here is the command from my DAO:

@Query("SELECT SubMenuTitle FROM SubMenus WHERE MenuID = :MenuID")
String[] getSubMenus(int MenuID);

When I run the query using the sqlite3 binary on my phone, the output is as expected.


Solution

  • This answer is many, many years late, but I got around this by altering the code to resemble the following:

    @Query("SELECT SubMenuTitle FROM SubMenus WHERE MenuID = :MenuID")
    LiveData<String[]> getSubMenus(int MenuID);
    

    Then, after creating a ViewModel object, the observe() method was implemented as follows:

    vm.getSubMenus(MenuID).observe(this, new Observer<String[]>() {
        @Override
        public void onChanged(@Nullable String[] menus) {
            populateTabs(menus);
        }
    });
    

    My understanding is that since the database queries take time to run, the instant that getSubMenus() is run, nothing is actually returned from the database. My initial flawed understanding was that Room would wait for the database query to finish running before returning the object, but 5 further years of studying has proven that this is not the case. Therefore, the LiveData<> wrapper was needed so that the String[] could be updated as data came in from the database. However, I may still be wrong, so someone please correct me if I am.