Java Android ROOM-如何观察LiveData更改(每次设置日历时)并将LiveData列表结果发送到适配器?

Java Android ROOM-如何观察LiveData更改(每次设置日历时)并将LiveData列表结果发送到适配器?,java,android,android-room,dao,android-livedata,Java,Android,Android Room,Dao,Android Livedata,我有一本书 要创建这个,我有一个CalendarFragment打开CustomCalendarView (扩展LinearLayout的类) 然后使用MyGridAdapter(扩展ArrayAdapter的类)构造日历 单击日历上的单元格时,您将进入一个新的活动,在该活动中,您可以保存一个包含一些信息(以及日历中单击的单元格的日期)的日志。 (此日志条目保存到我的数据库中) 我想在有日志项的所有日历单元格上显示圆圈 为此,我有一个方法changemount(),在该方法中,我将日历上所有可见

我有一本书

要创建这个,我有一个
CalendarFragment
打开
CustomCalendarView

(扩展LinearLayout的类)

然后使用
MyGridAdapter
(扩展ArrayAdapter的类)构造日历

单击日历上的单元格时,您将进入一个新的活动,在该活动中,您可以保存一个包含一些信息(以及日历中单击的单元格的日期)的日志。 (此日志条目保存到我的数据库中)

我想在有日志项的所有日历单元格上显示圆圈

为此,我有一个方法changemount(),在该方法中,我将日历上所有可见日期的列表传递给我的ViewModel,然后调用setFilter()方法,该方法检查可见日期列表并返回该特定月份日志条目数据库中存在的所有日期

如何从viewModel中观察结果列表:logEntryDatesFilteredByMonth,然后将其传递给适配器,以便执行UI更改

日历片段

public class CalendarFragment extends Fragment {

    CustomCalendarView customCalendarView;
    List<LogDates> dates = new ArrayList<>();
    LogEntriesViewModel logEntriesViewModel;
    MyGridAdapter myGridAdapter;

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

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        customCalendarView = (CustomCalendarView) getView().findViewById(R.id.custom_calendar_view);
        ((AppCompatActivity) getActivity()).getSupportActionBar().hide();

        customCalendarView.SetUpCalendar();
        logEntriesViewModel.getDatesFilteredByMonth().observe(this, logDates -> myGridAdapter.setData(logDates));
        Log.i("PRESENT_DATES", String.valueOf(dates));
    }
}

公共类CalendarFragment扩展了片段{
CustomCalendarView CustomCalendarView;
列表日期=新建ArrayList();
LogEntriesViewModel LogEntriesViewModel;
MyGridAdapter MyGridAdapter;
@可空
@凌驾
创建视图时的公共视图(@NonNull LayoutInflater inflater、@Nullable ViewGroup container、@Nullable Bundle savedInstanceState){
返回充气机。充气(R.layout.calendar\u activity\u main,container,false);
}
@凌驾
已创建视图上的公共void(视图,@Nullable Bundle savedInstanceState){
customCalendarView=(customCalendarView)getView().findViewById(R.id.custom\u calendar\u视图);
((AppCompatActivity)getActivity()).getSupportActionBar().hide();
customCalendarView.SetUpCalendar();
logEntriesViewModel.getDatesFilteredByMonth().observe(这是logDates->myGridAdapter.setData(logDates));
Log.i(“当前日期”,String.valueOf(日期));
}
}
CustomCalendarView


public class CustomCalendarView extends LinearLayout {

    private LogEntriesViewModel logEntriesViewModel;

    ImageButton NextButton, PreviousButton;
    TextView CurrentDate;
    GridView gridView;
    public static final int MAX_CALENDAR_DAYS = 42;
    Calendar calendar = Calendar.getInstance(Locale.ENGLISH);
    Context context;
    MyGridAdapter myGridAdapter;
    SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM yyyy", Locale.ENGLISH);
    SimpleDateFormat monthFormat = new SimpleDateFormat("MMMM", Locale.ENGLISH);
    SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy", Locale.ENGLISH);
    SimpleDateFormat eventDateFormat = new SimpleDateFormat(("dd-MM-yyyy"), Locale.ENGLISH);

    public static final String MY_PREFS_NAME = "MyPrefsFile";

    List<Date> dates = new ArrayList<>();

    List<LogDates> logsList = new ArrayList<>();

    List<String> datesFormattedList = new ArrayList<>();



    public CustomCalendarView(Context context) {
        super(context);
    }

    public CustomCalendarView(final Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        InitializeLayout();
        SetUpCalendar();

        PreviousButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, -1);
                SetUpCalendar();
            }
        });

        NextButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                calendar.add(Calendar.MONTH, 1);
                SetUpCalendar();
            }
        });

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setCancelable(true);

                final String date = eventDateFormat.format(dates.get(position));

                Intent i = new Intent(getContext(), WorkoutButtonsActivity.class);
                i.putExtra(WorkoutButtonsActivity.EXTRA_DATE, date);
                getContext().startActivity(i);
            }
        });
    }

    public CustomCalendarView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void InitializeLayout() {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.calendar_layout, this);
        NextButton = view.findViewById(R.id.nextBtn);
        PreviousButton = view.findViewById(R.id.previousBtn);
        CurrentDate = view.findViewById(R.id.current_Date);
        gridView = view.findViewById(R.id.gridview);
    }

    void SetUpCalendar() {

        datesFormattedList.clear();

        String currentDate = dateFormat.format(calendar.getTime());
        CurrentDate.setText(currentDate);
        dates.clear();
        Calendar monthCalendar = (Calendar) calendar.clone();
        monthCalendar.set(Calendar.DAY_OF_MONTH, 1);
        int FirstDayofMonth = monthCalendar.get(Calendar.DAY_OF_WEEK) - 2;
        monthCalendar.add(Calendar.DAY_OF_MONTH, -FirstDayofMonth);

        while (dates.size() < MAX_CALENDAR_DAYS) {
            dates.add(monthCalendar.getTime());
            monthCalendar.add(Calendar.DAY_OF_MONTH, 1);
        }
        /*THIS CONVERTS THE LIST OF ALL VISIBLE DATES TO A STRING */
        for (int i = 0; i< MAX_CALENDAR_DAYS; i++) {
            final String dateFormatted = eventDateFormat.format(dates.get(i));
            datesFormattedList.add(dateFormatted);
        }
        Log.i("Dates", String.valueOf(datesFormattedList));
        ChangeMonth();

        myGridAdapter = new MyGridAdapter(context, dates, calendar, logsList);
        gridView.setAdapter(myGridAdapter);
    }

    public void ChangeMonth() {
        logEntriesViewModel = ViewModelProviders.of((FragmentActivity) context).get(LogEntriesViewModel.class);
        logEntriesViewModel.setFilter(datesFormattedList);

    }
}

公共类CustomCalendarView扩展了LinearLayout{
专用LogEntriesViewModel LogEntriesViewModel;
ImageButton下一个按钮、上一个按钮;
文本视图当前日期;
GridView;
公共静态最终整数最大日历天数=42;
Calendar=Calendar.getInstance(Locale.ENGLISH);
语境;
MyGridAdapter MyGridAdapter;
SimpleDataFormat dateFormat=新的SimpleDataFormat(“MMMM yyyy”,Locale.ENGLISH);
SimpleDataFormat monthFormat=新的SimpleDataFormat(“MMMM”,Locale.ENGLISH);
SimpleDataFormat yearFormat=新的SimpleDataFormat(“yyy”,Locale.ENGLISH);
SimpleDataFormat eventDateFormat=新的SimpleDataFormat((“dd-MM-yyyy”),Locale.ENGLISH);
公共静态最终字符串MY\u PREFS\u NAME=“MyPrefsFile”;
列表日期=新建ArrayList();
List logsList=new ArrayList();
List datesFormattedList=新建ArrayList();
公共自定义日历视图(上下文){
超级(上下文);
}
公共CustomCalendarView(最终上下文,@Nullable AttributeSet attrs){
超级(上下文,attrs);
this.context=上下文;
InitializeLayout();
设置日历();
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
calendar.add(calendar.MONTH,-1);
设置日历();
}
});
setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
calendar.add(calendar.MONTH,1);
设置日历();
}
});
setOnItemClickListener(新的AdapterView.OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父对象、视图、整型位置、长id){
AlertDialog.Builder=新建AlertDialog.Builder(上下文);
builder.setCancelable(true);
最终字符串date=eventDateFormat.format(dates.get(position));
Intent i=新的Intent(getContext(),workoutbuttonactivity.class);
i、 putExtra(WorkoutButtonActivity.EXTRA_日期,日期);
getContext().startActivity(i);
}
});
}
公共CustomCalendarView(上下文上下文,@Nullable AttributeSet attrs,int-defStyleAttr){
super(上下文、attrs、defStyleAttr);
}
private void InitializeLayout(){
LayoutFlater充气器=(LayoutFlater)context.getSystemService(context.LAYOUT\u充气器\u服务);
视图=充气机。充气(R.layout.calendar\u布局,本);
NextButton=view.findviewbyd(R.id.nextBtn);
PreviousButton=view.findViewById(R.id.previousBtn);
CurrentDate=view.findviewbyd(R.id.current\u Date);
gridView=view.findviewbyd(R.id.gridView);
}
void SetUpCalendar(){
datesFormattedList.clear();
字符串currentDate=dateFormat.format(calendar.getTime());
CurrentDate.setText(CurrentDate);
日期。清除();
Calendar monthCalendar=(Calendar)Calendar.clone();
monthCalendar.set(日历月的第1天);
int FirstDayofMonth=monthCalendar.get(Calendar.DAY\u OF u WEEK)-2;
monthCalendar.add(Calendar.DAY\u OF\u MONTH,-firstday OF MONTH);
while(dates.size()public class LogEntriesViewModel extends AndroidViewModel {

    private LogEntriesRepository repository;
   // private LiveData<List<Log_Entries>> allLogEntries;
    private LiveData<List<Log_Entries>> allWorkoutLogEntries;



    private LiveData<List<LogDates>> logEntryDatesFilteredByMonth;
    private LiveData<List<LogDates>> allLogEntryDates;
    private MutableLiveData<List<String>> filterLogPresentDates = new MutableLiveData <List<String>>();



    public LogEntriesViewModel(@NonNull Application application) {
        super(application);
        repository = new LogEntriesRepository(application);
        allLogEntryDates = repository.getAllLogEntryDates();
        logEntryDatesFilteredByMonth = Transformations.switchMap(filterLogPresentDates, c -> repository.getAllDateLogEntries(c));
    }

    public LiveData<List<LogDates>> getDatesFilteredByMonth() { return logEntryDatesFilteredByMonth; }

    public void setFilter(List<String> currentMonthDates) { filterLogPresentDates.setValue(currentMonthDates); }
    LiveData<List<LogDates>> getAllLogEntryDates() { return allLogEntryDates; }


    public void insert(Log_Entries log_entries){
        repository.insert(log_entries);
    }
    public void update(Log_Entries log_entries){
        repository.update(log_entries);
    }
    public void delete(Log_Entries log_entries ) {
        repository.delete(log_entries);
    }

    public LiveData<List<Log_Entries>> getAllWorkoutLogEntries(int junctionID, String date){
        allWorkoutLogEntries = repository.getAllWorkoutLogEntries(junctionID, date);
        return allWorkoutLogEntries;
    }
}

@Dao
public interface Log_Entries_Dao {

    @Insert
    void insert(Log_Entries logEntry);

    @Update
    void update(Log_Entries logEntry);

    @Delete
    void delete(Log_Entries logEntry);


    @Query("SELECT * FROM log_entries_table")
    LiveData<List<Log_Entries>> getAllFromLogEntries();


    @Query("SELECT * FROM log_entries_table WHERE log_entries_table.junction_id = :junctionID AND log_entries_table.date = :date " )
    LiveData<List<Log_Entries>> getAllFromWorkoutLogEntries(int junctionID, String date);

    @Query("SELECT * FROM log_entries_table WHERE log_entries_table.date = :date " )
    LiveData<List<Log_Entries>> getAllDatesWithLogEntries(String date);

    @Query("SELECT date FROM log_entries_table WHERE log_entries_table.date = :date " )
    LiveData<List<LogDates>> getAllDatesWithLogs(List<String> date);

    @Query("SELECT date FROM log_entries_table " )
    LiveData<List<LogDates>> getAllLogEntryDates();

}

logEntriesViewModel.getDatesFilteredByMonth().observe(this, logDates -> yourAdapter.setData(logDates));