I'm following the ViewModel app architecture for android, and run in to a problem when retriving some simple data from the SQLite database. Here are the simplified version of my DAO, and my repo:
THE 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);
}
THE REPO:
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();
}
}
Problem is when I call the method getUserStuff(Long id)
from the repo, (which then calls the method from the DAO), I get a null ( Log.d(TAG,"[getuserStuff] the DAO returned ---> "+info.getValue());
prints a null). I have a button that prints everything I have in the database, and there is clearly data in it, and the DAO should return something. Example:
Calling geteverything():
D/UserStuffRepository: EVERYTHING IN THE DATABASE [UserStuff{id=1, path_to_user_profile_pic='/path/path'}]
Then calling getUserStuff(1)
returns a UserStuff with an id of 1, and a pathToUserProfilePic of null.
Do you see any clear problem, or should I post extra stuff like initializing the repo, the ViewModel, and some stuff from the MainActivity? Thanks!
Change your function to return a simple String
LiveData<String> getPathToUserProfilePic(Long id);
To this
String getPathToUserProfilePic(Long id);
And of course change how you get it
String info = userStuffDao.getPathToUserProfilePic(id);
Log.d(TAG," [getuserStuff] the dao returned ---> " + info);
I'm pretty sure you don't need a LiveData there because you save the String to UserStuff.
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.