簡體   English   中英

無法從SQLite中檢索簡單的字符串

[英]Can't retrieve a simple string from SQLite

我正在關注Android的ViewModel應用程序架構,並在從SQLite數據庫中重新獲取一些簡單數據時遇到問題。 這是我的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();
    }
}

問題是當我從repo調用方法getUserStuff(Long id) (然后從DAO調用該方法),我得到一個null( Log.d(TAG,"[getuserStuff] the DAO returned ---> "+info.getValue());打印一個null)。 我有一個按鈕,打印我在數據庫中的所有內容,其中有明顯的數據,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中的一些東西? 謝謝!

更改函數以返回簡單的String

LiveData<String> getPathToUserProfilePic(Long id);

對此

String getPathToUserProfilePic(Long id);

當然,改變你如何得到它

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

我很確定你不需要LiveData,因為你將String保存到UserStuff。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM