我正在使用适用于android的ViewModel应用程序体系结构,并从SQLite数据库中检索一些简单数据时遇到问题。这是我的DAO和我的仓库的简化版本:
DAO:
@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)
(然后从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,并且pathToUserProfilePic为null。
您是否看到任何明显的问题,还是我应该发布其他东西,例如初始化存储库,ViewModel和MainActivity中的一些东西?谢谢!
答案 0 :(得分:0)
更改您的函数以返回简单的String
LiveData<String> getPathToUserProfilePic(Long id);
对此
String getPathToUserProfilePic(Long id);
当然可以更改获取方式
String info = userStuffDao.getPathToUserProfilePic(id);
Log.d(TAG," [getuserStuff] the dao returned ---> " + info);
我很确定您在那里不需要LiveData,因为您已将字符串保存到UserStuff。