首页 > 解决方案 > 无法从 SQLite 检索简单字符串

问题描述

我正在遵循适用于 android 的 ViewModel 应用程序架构,并在从 SQLite 数据库中检索一些简单数据时遇到问题。这是我的 DAO 的简化版本和我的 repo:

道:

@Dao
public interface UserStuffDao {
    @Query("SELECT * from UserStuff")
    List < UserStuff > getAllUsers();

    @Query("SELECT path_to_user_profile_pic from UserStuff where id=:id")
    LiveData < String > getPathToUserProfilePic(Long id);
}

回购:

public class UserStuffRepository {
    private static UserStuffRepository instance;
    private static UserStuffDao userStuffDao;
    public static final String TAG = UserStuffRepository.class.getSimpleName();


    public static UserStuffRepository getInstance(Application application) {
        Log.d(TAG, "[getInstance] called");
        if (instance == null) {
            instance = new UserStuffRepository();
            Database db = Database.getDatabase(application.getApplicationContext());
            userStuffDao = db.userStuffDao();
        }
        return instance;
    }


    public MutableLiveData < UserStuff > getUserStuff(Long id) {
        final MutableLiveData < UserStuff > userData =
            new MutableLiveData < > ();

        LiveData < String > info = userStuffDao.getPathToUserProfilePic(id);
        Log.d(TAG, "[getuserStuff] the dao returned ---> " + info.getValue());
        UserStuff to_return = new UserStuff(id, info.getValue());
        userData.setValue(to_return);

        return userData;
    }

    public void geteverything() {

        new AsyncTask < Void, Void, Void > () {
            @Override
            protected Void doInBackground(Void...voids) {
                Log.d(TAG, " EVERYTHING IN THE DATABASE " + userStuffDao.getAllUsers());
                return null;
            }
        }.execute();
    }
}

问题是当我getUserStuff(Long id)从 repo 调用方法时(然后从 DAO 调用方法),我得到一个空值(Log.d(TAG,"[getuserStuff] the DAO returned ---> "+info.getValue());打印一个空值)。我有一个按钮,可以打印我在数据库中的所有内容,其中显然有数据,DAO 应该返回一些东西。例子:

打电话geteverything():

D/UserStuffRepository: EVERYTHING IN THE DATABASE [UserStuff{id=1, path_to_user_profile_pic='/path/path'}] 

然后调用getUserStuff(1)返回一个 ID 为 1 的 UserStuff,以及一个为 null 的 pathToUserProfilePic。

您是否看到任何明显的问题,或者我应该发布额外的内容,例如初始化 repo、ViewModel 和 MainActivity 中的一些内容?谢谢!

标签: javaandroidsqliteandroid-room

解决方案


更改您的函数以返回一个简单的字符串

LiveData<String> getPathToUserProfilePic(Long id);

对此

String getPathToUserProfilePic(Long id);

当然改变你得到它的方式

String info = userStuffDao.getPathToUserProfilePic(id);
Log.d(TAG," [getuserStuff] the dao returned ---> " + info);

我很确定您在那里不需要 LiveData,因为您将字符串保存到 UserStuff。


推荐阅读