在存储库空指针异常中使用AsyncTask的Android Room查询

时间:2019-03-25 22:15:08

标签: android android-asynctask android-room android-mvvm

我正在尝试使用ID查询保存在会议室本地数据库中的某些数据。我已经从序列化对象接收到ID,并将其传递给我的视图模型类,该视图模型类调用存储库以使用dao执行查询。

asynctask用于使事物异步并从db返回请求的值。我已经制作了一个接口,并在异步任务中对其进行了初始化,因此我可以从db返回结果,但NPE失败。

在活动中,我调用了存储库并传递了序列化数据,例如:

   public class ViewSessionActivity extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = ViewSessionActivity.class.getSimpleName();

    private Toolbar toolbar;
    private Sessions sessions; // serialized object from adapter

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_session);

        init();
        setSupportActionBar(toolbar);

    }

    private void init() {

        // skipped fvid calls

        sessions = (Sessions) getIntent().getSerializableExtra(Constants.SESSION_DETAIL_KEY);
        Log.d(TAG, "Prog id:\t" + sessions.prog_sessionId);

        //error occurs here which leads to async task call in repository
SessionsRepository.getRepository(getApplication()).getSessionByID(sessions.prog_sessionId); 

    }

以及在存储库中:

    public class SessionsRepository {

    private static final String TAG = SessionsRepository.class.getSimpleName();

    private SessionsDAO dao;
    private static SessionsRepository repository = null;

    private LiveData<List<Sessions>> allSessions;
    private MutableLiveData<Boolean> loadingState;

    private Context context;
    private final SportsDatabase database;

    public SessionsRepository(Application application) {
        database = SportsDatabase.getInstance(application);
        dao = database.sessionsDAO();
        allSessions = dao.getAllSessions();
        loadingState = new MutableLiveData<>();
        context = application.getApplicationContext();
    }

    public static SessionsRepository getRepository(Application context){
        if (repository == null){
            repository = new SessionsRepository(context);
        }
        return repository;
    }

    public void fetchSessions() {
        String coachId = new PrefsUtils(context).getCoachId();

        Call<SessionDetails> call = RestClient.getRestInstance().getSessionsService().fetchSessions(coachId);

        call.enqueue(new Callback<SessionDetails>() {
            @Override
            public void onResponse(Call<SessionDetails> call, Response<SessionDetails> response) {
                if (response.isSuccessful()) {
                    loadingState.postValue(false); // remove progress
                    SessionDetails details = response.body();
                    List<Sessions> sessions = details.getSessions();
//                    Log.d(TAG, "N/w sesh size:\t" + sessions.size());
                    saveSessions(sessions);
                }
            }

            @Override
            public void onFailure(Call<SessionDetails> call, Throwable t) {
                loadingState.postValue(false);
                Toast.makeText(context, "Error Fetching Sessions", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void saveSessions(List<Sessions> sessions) {
        new SaveSessionsTask(dao).execute(sessions);
    }

    // this method which calls the async task
    public void getSessionByID(String id){
        new FindSessionTask(dao, context).execute(id);
    }

    public LiveData<List<Sessions>> getSavedSessions() {
        return allSessions;
    }

    public class SaveSessionsTask extends AsyncTask<List<Sessions>, Void, Void> {
        private SessionsDAO dao;

        public SaveSessionsTask(SessionsDAO dao) {
            this.dao = dao;
        }

        @Override
        protected Void doInBackground(List<Sessions>... lists) {
            dao.addSessions(lists[0]);
            return null;
        }
    }

    public class FindSessionTask extends AsyncTask<String, Void, Sessions>{

        private SessionsDAO dao;
        private OnSessionResultCallback callback;

        public FindSessionTask(SessionsDAO dao, Context context) {
            this.dao = dao;
            this.callback = (OnSessionResultCallback) context;
        }

        @Override
        protected Sessions doInBackground(String... strings) {
            Sessions sessions = dao.getSessionById(strings[0]);
            return sessions;
        }

        @Override
        protected void onPostExecute(Sessions sessions) {
            super.onPostExecute(sessions);
            Log.d(SessionsRepository.TAG, "Session name:\t" + sessions.session_name);
        }
    }

    // need help in returning the session found from db in onpostexecute method


}

dao类:

@Dao
public interface SessionsDAO {

    @Insert
    void addSessions(List<Sessions> sessions);

    @Query("select * from sessions")
    LiveData<List<Sessions>> getAllSessions();

    @Query("select * from sessions where prog_sessionId = :id")
    Sessions getSessionById(String id); // here

}

和接口回调,以通过后执行方法在异步任务中接收数据:

    public interface OnSessionResultCallback {
       void onSessionFound(Sessions sessions);
    }

logcat错误:

   Caused by: java.lang.ClassCastException: sashi.in.ecosports.extras.App cannot be cast to sashi.in.ecosports.interfaces.OnSessionResultCallback
        at sashi.in.ecosports.rest.db.repositories.SessionsRepository$FindSessionTask.<init>(SessionsRepository.java:110)
        at sashi.in.ecosports.rest.db.repositories.SessionsRepository.getSessionByID(SessionsRepository.java:82)
        at sashi.in.ecosports.ui.activities.ViewSessionActivity.init(ViewSessionActivity.java:63)
        at sashi.in.ecosports.ui.activities.ViewSessionActivity.onCreate(ViewSessionActivity.java:38)
        at android.app.Activity.performCreate(Activity.java:6671)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
....

我原本希望注销找到的会话名称,但得到了NPE。有人可以帮我执行异步房间查询吗,使用实体字段作为搜索字符串从列表中返回整个实体。视图模型如何接收数据,我的界面是否必要?谢谢。

1 个答案:

答案 0 :(得分:2)

由于尝试打印session.session_name时会得到NPE,这意味着返回的会话对象为null,这可能会发生:

  1. 查询不正确(因为您选择的查询很好,我猜您传递的是错误的ID)

  2. 尚未插入具有该ID的任何记录时(在这种情况下,您必须调试插入过程并检查数据库以查看插入是否正确)

要在运行时检查数据库内容,可以轻松使用description

关于带空间的更新查询,您还可以使用内置的@Update注释,该注释通过其主键查找传递的对象并更新所有列,或者使用@Query注释更新特定的列( s)像@Query("UPDATE sessions SET session_name = :newName WHERE prog_sessionId = :id"),它用会话ID为session_name更新id列。下面是示例代码:

@Dao
public interface SessionsDAO {
    @Query("SELECT * FROM sessions")   // Retrieve all columns saved in sessions table
    LiveData<List<Sessions>> getAllSavedSessions();

    @Query("SELECT * FROM sessions WHERE prog_sessionId = :id")   // Retrieve a single session with all columns saved in sessions table
    Sessions findSessionWithId(String id);

    @Query("SELECT session_name FROM sessions WHERE prog_sessionId = :id")   // Retrieve a single session name saved in sessions table
    String getSessionNameWithId(String id);

    @Update   // Update all non-primary columns of a session
    void updateSession(Sessions session);

    @Query("UPDATE sessions SET session_name = :newName")   // Update session_name column of all saved sessions
    void updateAllSessionNamesTo(String newName);

    @Query("UPDATE sessions SET session_name = :newName WHERE prog_sessionId = :id")   // Update session_name column of a session located with its id
    void updateSessionNameTo(String newName, String id);

    @Query("UPDATE sessions SET session_name = :newName AND session_date = :newDate WHERE prog_sessionId = :id")   // Update session_name and session_date column of a session located with its id
    void updateSessionNameAndDateTo(String newName, long newDate, String id);
}

如果需要在辅助线程上运行查询,可以使用Java执行程序,这是一个检索会话名称的简单示例:

@Dao
public abstract class SessionsDAO {
    void getSessionNameWithId(final String id, final NameLoadedListener onFinishListener) {
        Executors.newSingleThreadExecuter().submit(new Runnable() {
             @Override
             public void run() {
                 String name = getSessionNameWithId(id);
                 onFinishListener.onNameLoaded(name);
             }
        });
    }

    @Query("SELECT session_name FROM sessions WHERE prog_sessionId = :id")   // Retrieve a single session name saved in sessions table
    abstract String getSessionNameWithId(String id);

    public interface NameLoadedListener {
        void onNameLoaded(String name);
    }
}

这是通过检索实体并最后返回更新的实体来更新会话名称的示例。

@Dao
public abstract class SessionsDAO {
    void updateSessionNameWithId(final String id, final String newName, final SessionUpdateListener onFinishListener) {
        Executors.newSingleThreadExecuter().submit(new Runnable() {
             @Override
             public void run() {
                 updateSessionName(id, newName, onFinishListener);
             }
        });
    }

    @Transaction
    void updateSessionName(String id, String newName, SessionUpdateListener onFinishListener) {
         Sessions session = findSessionWithId(id);
         session.setName(newName);
         updateSession(session);
         onFinishListener.onSessionUpdated(session);
    }

    @Query("SELECT * FROM sessions WHERE prog_sessionId = :id")   // Retrieve a single session with all columns saved in sessions table
    Sessions findSessionWithId(String id);

    @Update   // Update all non-primary columns of a session
    void updateSession(Sessions session);

    public interface SessionUpdateListener {
        void onSessionUpdated(Sessions session);
    }
}

希望您能得到备忘录。