java - 无法从 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 中的一些内容?谢谢!
解决方案
更改您的函数以返回一个简单的字符串
LiveData<String> getPathToUserProfilePic(Long id);
对此
String getPathToUserProfilePic(Long id);
当然改变你得到它的方式
String info = userStuffDao.getPathToUserProfilePic(id);
Log.d(TAG," [getuserStuff] the dao returned ---> " + info);
我很确定您在那里不需要 LiveData,因为您将字符串保存到 UserStuff。
推荐阅读
- computer-vision - 智能手机相机运动估计 - 检测退化情况
- validation - 限制用户在更新和保存另一个依赖字段之前更新一个字段
- python - PHP:调用 python 脚本会引发 ModuleNotFoundError,从终端调用是否正常?
- c++ - 错误:助记符中的字符“(”无效
- multithreading - 使用条件变量的死锁
- typescript - 带有一般错误的打字稿缩小类型
- r - 错误:尝试在简单方程中应用非函数
- json - 试图解析 access.log
- amazon-web-services - 从 AWS 中的快照创建 EC2 实例?
- javascript - 重构下拉列表