LiveData在向Room DB添加新条目时未调用观察者

时间:2019-06-25 10:02:04

标签: android android-room android-livedata

我正在使用Room DB来存储用户设置的价格警报。

“警报”列表显示在带有按钮的片段中,该按钮可启动新活动以添加新条目。

当我添加一个新条目并返回到片段时,即使我返回LiveData并添加了一个Observer,RecyclerView也不会被更新。 我在这里尝试了多个答案,例如使用MutableLiveData而不是LiveData以及其他几个答案,但仍然无法正常工作。

我在这里尝试了多个答案,例如使用MutableLiveData代替LiveData,还有其他几个答案,但仍然无法正常工作。

DOA

    @Dao
    public interface PriceAlertDoa {

        public String tableName = DBContract.ALERTS_TABLE_NAME;

        @Query("SELECT * FROM " + tableName)
        public LiveData<List<PriceAlert>> getAll();

        @Query("SELECT * FROM " + tableName + " WHERE " + DBContract.ALERTS_COL_COINID + " LIKE :coinId")
        public List<PriceAlert> getByCoinId(String coinId);

        @Query("SELECT COUNT(*) FROM " + DBContract.ALERTS_TABLE_NAME)
        public int countUsers();

        @Insert(onConflict = OnConflictStrategy.REPLACE)
        public void insertAll(PriceAlert... priceAlerts);

        @Delete
        public void deleteAll(PriceAlert... priceAlert);

        @Update
        public void updateAll(PriceAlert... priceAlert);

    }

存储库

public class PriceAlertRepository {
    private PriceAlertDatabase alertsDb;
    private Context mContext;

    public PriceAlertRepository(Context context){
        mContext = context;

        if(alertsDb == null){
            alertsDb = Room.databaseBuilder(mContext.getApplicationContext(),
                    PriceAlertDatabase.class, DBContract.ALERTS_TABLE_NAME)
                    .build();
        }
    }


    public void insertAlert(PriceAlert priceAlert) {
        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
                alertsDb.priceAlertDoa().insertAll(priceAlert);
                return null;
            }
        }.execute();
    }

    public LiveData<List<PriceAlert>> getAllAlerts(){
        return alertsDb.priceAlertDoa().getAll();
    }

    public void deleteAlert(PriceAlert priceAlert){
        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
                alertsDb.priceAlertDoa().deleteAll(priceAlert);
                return null;
            }
        }.execute();
    }

    public void updateAlert(PriceAlert priceAlert){
        new AsyncTask<Void, Void, Void>(){
            @Override
            protected Void doInBackground(Void... voids) {
                alertsDb.priceAlertDoa().updateAll(priceAlert);
                return null;
            }
        }.execute();
    }
}

ViewModel

public class AlertsViewModel extends AndroidViewModel {
    private PriceAlertRepository mAlertRepository;
    private LiveData<List<PriceAlert>> mAlertList;

    public AlertsViewModel(@NonNull Application application) {
        super(application);

        mAlertRepository = new PriceAlertRepository(application);

        mAlertList = mAlertRepository.getAllAlerts();
    }

    public LiveData<List<PriceAlert>> getAllAlerts(){
        return mAlertList;
    }
}

显示警报列表的片段

public class AlertsListFragment extends Fragment {
    @BindView(R.id.recyclerView_Alerts)
    RecyclerView rvAlerts;
    @BindView(R.id.button_AddAlert)
    Button btnAddAlert;

    private Context mContext;
    private AlertsViewModel alertsViewModel;

    public AlertsListFragment(Context context) {
        mContext = context;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_alerts_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        ButterKnife.bind(this, view);

        rvAlerts.setHasFixedSize(true);
        rvAlerts.setLayoutManager(new LinearLayoutManager(mContext));

        alertsViewModel = ViewModelProviders.of(this).get(AlertsViewModel.class);

        btnAddAlert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Utils.launchActivity(mContext, AddAlertActivity.class);
            }
        });

        AlertsListAdapter adapter = new AlertsListAdapter(mContext);
        rvAlerts.setAdapter(adapter);



        alertsViewModel.getAllAlerts().observe(getViewLifecycleOwner(), new Observer<List<PriceAlert>>() {
            @Override
            public void onChanged(List<PriceAlert> priceAlerts) {
                Log.d("LIVE DATA", "Table updated: " + priceAlerts.size());
                adapter.updateData(priceAlerts);
            }
        });
    }

}

谢谢。

0 个答案:

没有答案