Как получить доступ к данным из базы данных комнаты внутри класса BroadcastReceiver - PullRequest
0 голосов
/ 04 мая 2020

Мне нужно получить доступ к данным из моей базы данных Room внутри класса BroadCastReceiver, но, как вы знаете, нам нужен владелец жизненного цикла, чтобы получить экземпляр класса ViewModel, как показано ниже.

public class AlertReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationHelper.sendFinanceLoggingNotification(context);
        RecurrenceInfoViewModel recurrenceInfoViewModel = new ViewModelProvider(this).get(RecurrenceInfoViewModel.class);

    }
}

при передаче "this "как владелец жизненного цикла android студия выдает ошибку. Может ли кто-нибудь подсказать мне, откуда я могу получить владельца жизненного цикла внутри BroadCastReceiver, или вы можете предложить какой-либо другой способ доступа к данным. Ниже приведены мои классы ViewModel и Repository

    public class RecurrenceInfoViewModel extends AndroidViewModel {


    private LiveData<List<RecurrenceInfoEntity>> allRecurrenceInfos;
    private RecurrenceInfoRepository recurrenceInfoRepository;

    public RecurrenceInfoViewModel(@NonNull Application application) {
        super(application);
        recurrenceInfoRepository=new RecurrenceInfoRepository(application);


    }

    public void insertRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {
        recurrenceInfoRepository.insertRecurrenceInfo(recurrenceInfoEntity);
    }

    public void updateRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {

        recurrenceInfoRepository.updateRecurrenceInfo(recurrenceInfoEntity);
    }

    public void deleteRecurrenceInfo(RecurrenceInfoEntity recurrenceInfoEntity) {
        recurrenceInfoRepository.deleteRecurrenceInfo(recurrenceInfoEntity);
    }

    public void deleteAllRecurrenceInfos() {
        recurrenceInfoRepository.deleteAllRecurrenceInfo();
    }



    public LiveData<RecurrenceInfoEntity> getAllRecurrenceInfos(String recurrenceInfoKey) {
        return recurrenceInfoRepository.getRecurrenceInfoEntityList(recurrenceInfoKey);
    }
}





public class RecurrenceInfoRepository {


    private RecurrenceInfoDao recurrenceInfoEntityDao;
    private LiveData<List<RecurrenceInfoEntity>> recurrenceInfoEntityList;

    public RecurrenceInfoRepository(Context context) {

        MoneyManagerDatabase moneyManagerDatabase = MoneyManagerDatabase.getInstance(context);
        recurrenceInfoEntityDao = moneyManagerDatabase.getRecurrenceInfoDao();
        recurrenceInfoEntityList = recurrenceInfoEntityDao.getAllRecurrenceInfo();


    }

    public void insertRecurrenceInfo(RecurrenceInfoEntity data) {

        new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
                Constants.INSERT_SINGLE_NODE_DATABASE_OPERATION).execute(data);
    }

    public void updateRecurrenceInfo(RecurrenceInfoEntity data) {
        new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
                Constants.UPDATE_SINGLE_NODE_DATABASE_OPERATION).execute(data);
    }

    public void deleteRecurrenceInfo(RecurrenceInfoEntity data) {
        new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
                Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION).execute(data);
    }

    public void deleteRecurrenceInfo(String  type) {
        new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
                Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION).execute();
    }

    public void deleteAllRecurrenceInfo() {
        new PerformSingleColumnDataOperations(recurrenceInfoEntityDao,
                Constants.DELETE_ALL_NODES_DATABASE_OPERATION).execute();
    }

    public LiveData<RecurrenceInfoEntity> getRecurrenceInfoEntityList(String key) {
        return recurrenceInfoEntityDao.getAllRecurrenceInfo(key);
    }


    private static class PerformSingleColumnDataOperations extends AsyncTask<RecurrenceInfoEntity, Void, Void> {

        private RecurrenceInfoDao dataDao;
        private String operationType;


        PerformSingleColumnDataOperations(RecurrenceInfoDao dataDao, String operationType) {
            this.dataDao = dataDao;
            this.operationType = operationType;

        }

        @Override
        protected Void doInBackground(RecurrenceInfoEntity... recurrenceInfoEntities) {
            switch (operationType) {
                case Constants.INSERT_SINGLE_NODE_DATABASE_OPERATION:
                    dataDao.insertRecurrenceInfo(recurrenceInfoEntities[0]);
                    break;
                case Constants.UPDATE_SINGLE_NODE_DATABASE_OPERATION:
                    dataDao.updateRecurrenceInfo(recurrenceInfoEntities[0]);
                    break;
                case Constants.DELETE_SINGLE_NODE_DATABASE_OPERATION:
                    dataDao.deleteRecurrenceInfo(recurrenceInfoEntities[0]);
                    break;
                case Constants.DELETE_ALL_NODES_DATABASE_OPERATION:
                    dataDao.deleteAllRecurrenceInfo();
            }

            return null;
        }
    }




}

Заранее спасибо.

1 Ответ

0 голосов
/ 05 мая 2020

Я решил вышеуказанную проблему, НЕ используя LiveData. Вы можете получить доступ к данным из Room в любом месте, просто предоставив ApplicationContext, как показано ниже.

DAO:

@Query("SELECT * FROM reference_info where recurrenceInfoPrimaryKey=:recurrenceinfoprimkey")
    RecurrenceInfoEntity getAllRecurrenceInfoWithOutLiveData(String recurrenceinfoprimkey);

Репозиторий:

  public RecurrenceInfoEntity getRecurrenceInfoEntityWithOutLiveData(String key) {
        return recurrenceInfoEntityDao.getAllRecurrenceInfoWithOutLiveData(key);
    }

BroadCastReceiver:

    public class AlertReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
new Thread(() -> {          
      RecurrenceInfoEntity recurrenceInfoEntity = 
     recurrenceInfoRepository.getRecurrenceInfoEntityWithOutLiveData(Constants.LOG_FINANCES_RECURRENCE_KEY);

         }).start();
        }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...