简体   繁体   中英

get data out of room database to from a livedata object

Good day,

I need some help with LiveData and Room database. The idea I have is that I want to allow the user to backup the contents of a Room database with a click of the button, which will then save the contents of the database as JSON file.

The issue I have is the following:

I want to get the data out of the database when the user clicks the button to backup the database. My app is structured like this:

Dao

@Query("SELECT * FROM media")
LiveData<List<Media>> getAll();

Repository

private final MediaDao mMediaDao;
public LiveData<List<Media>> getListOfMedia() {
    return mMediaDao.getAll();
}

ViewModel

public LiveData<List<Media>> getMedia() {
    return mMediaRepository.getListOfMedia();
}

Normally what I would do is observe the LiveData on the Fragment and any changes will then get me the data from the live data object. Thing is the data doesnt "change" per say.

So how can I get the data out of the Livedata object when the user clicks the button?

This might be a bit late, but you can create numerous query methods for the same dataset.

For example, I have two methods fetching the same data, one returning a LiveData<List<Media>> object, and one returning List<Media> , like so:

@Query("SELECT * FROM media")
LiveData<List<Media>> getLiveAll();

@Query("SELECT * FROM media")
List<Media> getAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM