Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/205.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 如何从LiveData中获取值?_Android_Android Sqlite_Android Room_Android Livedata - Fatal编程技术网

Android 如何从LiveData中获取值?

Android 如何从LiveData中获取值?,android,android-sqlite,android-room,android-livedata,Android,Android Sqlite,Android Room,Android Livedata,我是第一次使用这个房间。我正在研究LiveData的概念。我知道我们可以将DB中的记录提取到LiveData中,并附加观察者 @Query("SELECT * FROM users") <LiveData<List<TCUser>> getAll(); @Query(“从用户中选择*) 如果我正确理解了您的体系结构,那么updateUsers位于AsyncTask或类似任务中 这是我建议的方法,包括调整Dao以获得最大的效率。您编写了许多代码来做出您可以要求数据

我是第一次使用这个房间。我正在研究LiveData的概念。我知道我们可以将DB中的记录提取到LiveData中,并附加观察者

@Query("SELECT * FROM users")

<LiveData<List<TCUser>> getAll();
@Query(“从用户中选择*)

如果我正确理解了您的体系结构,那么updateUsers位于AsyncTask或类似任务中

这是我建议的方法,包括调整Dao以获得最大的效率。您编写了许多代码来做出您可以要求数据库做出的决策

这也是不紧凑或效率不高的代码,但我希望它能说明如何更有效地使用这些库

后台线程(IntentService、AsyncTask等):


除非我对数据进行处理,否则我不会将数据插入数据库,所以使用上面提到的代码真的有帮助吗?这非常有用,因为数据库查询是同步操作,使用LiveData观察其输出可以避免大量样板代码。你在这里的问题似乎与最初提出的问题不同。您是否可以编辑您的问题,以包含有关数据获取和“处理”架构的详细信息?谢谢您的详细回答。谢谢。但您要解释的是,当我获取onChanged()方法事件时,一旦数据库中的数据被更新/添加/删除,就会采取措施。但我想做的是,在将一组新数据插入数据库之前,我需要获取旧记录并处理从服务器接收到的新数据,然后更新数据库。你对我的解释我确实理解,但那不是我想要的。你的问题是如何从服务器检索数据?一条重要的经验法则:除非你必须执行优化,否则总是选择更短、更简单的代码。维修性>效率您是否会稍微整理一下您的问题,以便更清楚地了解您正在引入LiveData的体系结构?还是只创建一个查询,检查用户是否存在,而不是返回整个用户行?@Sneha:请将答案标记为已接受或澄清问题请参阅编辑的答案
<LiveData<List<TCUser>> getAll().getValue()
List<User>serverUsers: Is the data received from a response from an API

private void updateUsers(List<User> serverUsers) {
    List<UserWithShifts> users = appDatabase.userDao().getAllUsers();
    HashMap<String, User> ids = new HashMap();
    HashMap<String, User> newIds = new HashMap();

    if (users != null) {
        for (UserWithShifts localUser : users) {
            ids.put(localUser.user.getId(), localUser.user);
        }
    }

    for (User serverUser : serverUsers) {
        newIds.put(serverUser.getId(), serverUser);

        if (!ids.containsKey(serverUser.getId())) {
            saveShiftForUser(serverUser);
        } else {
            User existingUser = ids.get(serverUser.getId());
            //If server data is newer than local
            if (DateTimeUtils.isLaterThan(serverUser.getUpdatedAt(), existingUser.getUpdatedAt())) {
                deleteEventsAndShifts(serverUser.getId());
                saveShiftForUser(serverUser);
            }
        }
    }
@Query("SELECT * FROM users")
List<UserWithShifts> getAllUsers();
<LiveData<List<User>> getAll().getValue()
/*
 * assuming this method is executing on a background thread
 */
private void updateUsers(/* from API call */List<User> serverUsers) {
    for(User serverUser : serverUsers){
        switch(appDatabase.userDao().userExistsSynchronous(serverUser.getId())){
            case 0: //doesn't exist
                saveShiftForUser(serverUser);
            case 1: //does exist
                UserWithShifts localUser = appDatabase.userDao().getOldUserSynchronous(serverUser.getId(), serverUser.getUpdatedAt());
                if(localUser != null){ //there is a record that's too old
                    deleteEventsAndShifts(serverUser.getId());
                    saveShiftForUser(serverUser);
                }
            default: //something happened, log an error
        }
    }
}
/*
 * If you receive the IllegalStateException, try this code
 *
 * NOTE: This code is not well architected. I would recommend refactoring if you need to do this to make things more elegant.
 *
 * Also, RxJava is better suited to this use case than LiveData, but this may be easier for you to get started with
 */
private void updateUsers(/* from API call */List<User> serverUsers) {
    for(User serverUser : serverUsers){
        final LiveData<Integer> userExistsLiveData = appDatabase.userDao().userExists(serverUser.getId());
        userExistsLiveData.observe(/*activity or fragment*/ context, exists -> {
            userExistsLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
            switch(exists){
                case 0: //doesn't exist
                    saveShiftForUser(serverUser);
                case 1: //does exist
                    final LiveData<UserWithShifts> localUserLiveData = appDatabase.userDao().getOldUser(serverUser.getId(), serverUser.getUpdatedAt());
                    localUserLiveData.observe(/*activity or fragment*/ context, localUser -> { //this observer won't be called unless the local data is out of date
                        localUserLiveData.removeObservers(context); //call this so that this same code block isn't executed again. Remember, observers are fired when the result of the query changes.
                        deleteEventsAndShifts(serverUser.getId());
                        saveShiftForUser(serverUser);
                    });
                default: //something happened, log an error
            }
        });
    }
}
@Dao
public interface UserDao{
    /*
     * LiveData should be chosen for most use cases as running on the main thread will result in the error described on the other method
     */
    @Query("SELECT * FROM users")
    LiveData<List<UserWithShifts>> getAllUsers();

    /*
     * If you attempt to call this method on the main thread, you will receive the following error:
     *
     * Caused by: java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long periods of time.
     *  at android.arch.persistence.room.RoomDatabase.assertNotMainThread(AppDatabase.java:XXX)
     *  at android.arch.persistence.room.RoomDatabase.query(AppDatabase.java:XXX)
     *
     */
    @Query("SELECT * FROM users")
    List<UserWithShifts> getAllUsersSynchronous();

    @Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
    LiveData<Integer> userExists(String id);

    @Query("SELECT EXISTS (SELECT * FROM users WHERE id = :id)")
    Integer userExistsSynchronous(String id);

    @Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
    LiveData<UserWithShifts> getOldUser(String id, Long updatedAt);

    @Query("SELECT * FROM users WHERE id = :id AND updatedAt < :updatedAt LIMIT 1")
    UserWithShifts getOldUserSynchronous(String id, Long updatedAt);
}
public class UserDaoWrapper {
    private final UserDao userDao;

    public UserDaoWrapper(UserDao userDao) {
        this.userDao = userDao;
    }

    public LiveData<Long[]> insertAsync(UserWithShifts... users){
        final MutableLiveData<Long[]> keys = new MutableLiveData<>();
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> keys.postValue(userDao.insert(users)));
        return keys;
    }

    public void updateAsync(UserWithShifts...users){
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> {
            userDao.update(users);
        });
    }

    public void deleteAsync(User... users){
        HandlerThread ht = new HandlerThread("");
        ht.start();
        Handler h = new Handler(ht.getLooper());
        h.post(() -> {
            for(User e : users)
                userDao.delete(e.getId());
        });
    }
}