question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How display events from database

See original GitHub issue

Hello everyone, I wrote 2 days ago about displaing data to calendar.I watch the sample , try many ways , but I dont understand what I am doing wrong.My code

public class WeekViewCalendarFragment extends Fragment implements WeekView.EventClickListener, MonthLoader.MonthChangeListener, WeekView.EventLongPressListener, WeekView.EmptyViewLongPressListener, WeekView.EmptyViewClickListener {

    private WeekView mWeekView;
    private int mWeekViewType = TYPE_THREE_DAY_VIEW;
    private List<WeekViewEvent> mNewEvents;
    private long mEeventId;
    private Event mEvent;
    private List<Event> mEvents;

    private static final String TAG = "tag";
    private static final int TYPE_DAY_VIEW = 1;
    private static final int TYPE_THREE_DAY_VIEW = 2;
    private static final int TYPE_WEEK_VIEW = 3;


    /*********************************************
     *Обязательный интерфейс для активности хоста*
     ********************************************/
    public interface CallbacksEvent{
        void onEventSelected(Event event);
    }

    public WeekViewCalendarFragment(){

    }

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        mNewEvents = new ArrayList<>();

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_calendar_week_view,container,false);

        // Inflate the layout for this fragment
        mWeekView = (WeekView) view.findViewById(R.id.calendar_week_view);

        // Show a toast message about the touched event.
        mWeekView.setOnEventClickListener(this);

        // The week view has infinite scrolling horizontally. We have to provide the events of a
        // month every time the month changes on the week view.
        mWeekView.setMonthChangeListener(this);

        // Set long press listener for events.
        mWeekView.setEventLongPressListener(this);

        // Set long press listener for empty view
        mWeekView.setEmptyViewLongPressListener(this);

        mWeekView.setEmptyViewClickListener(this);

        mWeekView.notifyDatasetChanged();

        return view;
    }

    public long getEeventId() {
        mEeventId++;
        return mEeventId;
    }

    public void setEeventId(long eventId) {
        mEeventId = eventId;
    }

    @Override
    public void onEventClick(WeekViewEvent event, RectF eventRect) {

        Intent intent = new Intent(getActivity(),CalendarReviewEventActivity.class);
        intent.putExtra("title",event.getName());
        intent.putExtra("start_time",event.getStartTime().getTime());
        intent.putExtra("end_time",event.getEndTime().getTime());
        intent.putExtra("id",event.getId());
        startActivity(intent);


        Toast.makeText(getActivity(),"Clicked " + event.getName(),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onEventLongPress(final WeekViewEvent event, RectF eventRect) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Delete event?")
                .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mNewEvents.remove(event);

                        mWeekView.notifyDatasetChanged();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

    }

    @Override
    public void onEmptyViewLongPress(Calendar time) {
        Toast.makeText(getActivity(),"Empty view long press " + getEventTitle(time),Toast.LENGTH_SHORT ).show();
    }



    @Override
    public void onEmptyViewClicked(Calendar time){

        Intent intent = new Intent(getActivity(),CalendarAddEventActivity.class);
        startActivity(intent);

        // Set the new event with duration one hour.
        Calendar endTimeEvent = (Calendar) time.clone();
        endTimeEvent.add(Calendar.HOUR,2);

        String title = "Event";

        mEvent = new Event(UUID.randomUUID(),"Event",time,endTimeEvent);
        EventLab.get(getActivity()).addEvent(mEvent);


        // Refresh the week view. onMonthChange will be called again.
        mWeekView.notifyDatasetChanged();

        Toast.makeText(getActivity(),"Empty view click" + getEventTitle(time),Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);

    }

    @Override
    public List<WeekViewEvent> onMonthChange(int newYear, int newMonth) {

        List<WeekViewEvent> events = new ArrayList<>();
        ArrayList<WeekViewEvent> newEvents = getNewEvents(newYear, newMonth);
        events.addAll(newEvents);

        return events;
    }

    private ArrayList<WeekViewEvent> getNewEvents(int year,int month){
        // Get the starting point and ending point of the given month. We need this to find the
        // events of the given month

        Event event = new Event();
        Date start = new Date();
        Date end = new Date();

        start = event.getStartEvent();
        end = event.getEndEvent();

        Calendar startTime = Calendar.getInstance();
        startTime.setTime(start);
        startTime.set(Calendar.YEAR, startTime.get(Calendar.YEAR));
        startTime.set(Calendar.MONTH, startTime.get(Calendar.MONTH));
        startTime.set(Calendar.DAY_OF_MONTH, startTime.get(Calendar.DAY_OF_MONTH));
        startTime.set(Calendar.HOUR_OF_DAY,startTime.get(Calendar.HOUR_OF_DAY));
        startTime.set(Calendar.MINUTE,startTime.get(Calendar.MINUTE));
        Calendar endTime = (Calendar) startTime.clone();
        endTime.setTime(end);
        endTime.set(Calendar.YEAR, startTime.get(Calendar.YEAR));
        endTime.set(Calendar.MONTH, startTime.get(Calendar.MONTH));
        endTime.set(Calendar.DAY_OF_MONTH, startTime.get(Calendar.DAY_OF_MONTH));
        endTime.set(Calendar.HOUR_OF_DAY,endTime.get(Calendar.HOUR_OF_DAY));
        endTime.set(Calendar.MINUTE,endTime.get(Calendar.MINUTE));


        // Create a new event.
        WeekViewEvent eventing = new WeekViewEvent(getEeventId(),"New event",startTime,endTime);
        mNewEvents.add(eventing);

        ArrayList<WeekViewEvent> events = new ArrayList<>();
        for(WeekViewEvent evented:mNewEvents) {
            if (event.getEndTime().getTimeInMillis() > startTime.getTimeInMillis() &&
                    event.getStartTime().getTimeInMillis() < endTime.getTimeInMillis()) {
                events.add(evented);
            }
        }
        return events;
    }


    protected String getEventTitle(Calendar time){
        return String.format("Event of %02d:%02d %s/%d", time.get(Calendar.HOUR_OF_DAY),time.get(Calendar.MINUTE),time.get(Calendar.MONTH)+ 1, time.get(Calendar.DAY_OF_MONTH));
    }

    @Override
    public void onCreateOptionsMenu(Menu menu,MenuInflater inflater){
        super.onCreateOptionsMenu(menu,inflater);
        inflater.inflate(R.menu.calendar_fragment_menu,menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item){
        int id = item.getItemId();
        setupDateTimeInterpretator(id == R.id.calendar_week_view_seven_days_view);
        switch (id){
            case R.id.calendar_week_view_add_new_event:
                Intent intent = new Intent(getActivity(),CalendarAddEventActivity.class);
                startActivity(intent);
                return true;
            case R.id.calendar_week_view_today:
                mWeekView.goToToday();
                return true;
            case R.id.calendar_week_view_one_day_view:
                if(mWeekViewType != TYPE_DAY_VIEW){
                    item.setChecked(!item.isChecked());
                    mWeekViewType = TYPE_DAY_VIEW;
                    mWeekView.setNumberOfVisibleDays(1);

                    // Изменить размеры вида для одного дня
                    mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,8,getResources().getDisplayMetrics()));
                    mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,12,getResources().getDisplayMetrics()));
                    mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,12,getResources().getDisplayMetrics()));
                }
                return true;
            case R.id.calendar_week_view_three_days_view:
                if (mWeekViewType != TYPE_THREE_DAY_VIEW) {
                    item.setChecked(!item.isChecked());
                    mWeekViewType = TYPE_THREE_DAY_VIEW;
                    mWeekView.setNumberOfVisibleDays(3);

                    //Изменить размеры вида для трьох дней
                    mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 8, getResources().getDisplayMetrics()));
                    mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
                    mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 12, getResources().getDisplayMetrics()));
                    return true;
                }
            case R.id.calendar_week_view_seven_days_view:
                if(mWeekViewType != TYPE_WEEK_VIEW){
                    item.setChecked(!item.isChecked());
                    mWeekViewType = TYPE_WEEK_VIEW;
                    mWeekView.setNumberOfVisibleDays(7);

                    //Изменить размеры вида для недели
                    mWeekView.setColumnGap((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, getResources().getDisplayMetrics()));
                    mWeekView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
                    mWeekView.setEventTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 10, getResources().getDisplayMetrics()));
                }
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private void setupDateTimeInterpretator(final boolean shortDate){
        mWeekView.setDateTimeInterpreter(new DateTimeInterpreter() {
            @Override
            public String interpretDate(Calendar date) {
                SimpleDateFormat weekdayNameFormat = new SimpleDateFormat("EEE ", Locale.getDefault());
                String weekday = weekdayNameFormat.format(date.getTime());
                SimpleDateFormat format = new SimpleDateFormat("M/d", Locale.getDefault());

                if(shortDate){
                    weekday = String.valueOf(weekday.charAt(0));
                }

                return weekday.toUpperCase() + format.format(date.getTime());
            }

            @Override
            public String interpretTime(int hour) {
                return hour > 11 ? (hour - 12) + "PM" : (hour == 0 ? "12AM" : hour + "AM");
            }
        });
    }
}```

```java
public class Event extends WeekViewEvent{

    private UUID mEventId;
    private String mTitle;
    private String mDescription;
    private String mPeople;
    private String mPlace;
    private int mColor;
    private int mDayOfMonth;

    private Date mStartEvent = new Date();
    private Date mEndEvent = new Date();


    public int getDayOfMonth() {
        return mDayOfMonth;
    }

    public void setDayOfMonth(int dayOfMonth) {
        mDayOfMonth = dayOfMonth;
    }


    public Date getEndEvent() {
        return mEndEvent;
    }


    public void setEndEvent(Calendar calendar) {
        mEndEvent = calendar.getTime();
    }

    public Date getStartEvent() {
        return mStartEvent;
    }


    public void setStartEvent(Calendar calendar) {
        mStartEvent = calendar.getTime();
    }



    public UUID getEventId() {
        return mEventId;
    }

    public void setEventId(UUID eventId) {
        mEventId = eventId;
    }

    public String getDescription() {
        return mDescription;
    }

    public void setDescription(String description) {
        mDescription = description;
    }

    public String getTitle() {
        return mTitle;
    }

    public void setTitle(String title) {
        mTitle = title;
    }

    public String getPeople() {
        return mPeople;
    }

    public void setPeople(String people) {
        mPeople = people;
    }



    public String getPlace() {
        return mPlace;
    }

    public void setPlace(String place) {
        mPlace = place;
    }

    @Override
    public int getColor() {
        return mColor;
    }

    @Override
    public void setColor(int color) {
        mColor = color;
    }

    public Event(){
        this(UUID.randomUUID());
    }

    public Event(UUID uuid){
        mEventId = uuid;
    }


    public Event(UUID id,String name){

        this.mEventId = id;
        this.mTitle = name;
    }

    public Event(UUID id, String name, Calendar startTime, Calendar endTime){

        setStartEvent(startTime);
        setEndEvent(endTime);

        this.mEventId = id;
        this.mTitle = name;
    }
}

`public class EventLab { private static EventLab sEventLab; private SQLiteDatabase mDatabase;

public static EventLab get(Context context){
    if(sEventLab == null){
        sEventLab = new EventLab(context);
    }
    return sEventLab;
}

private EventLab(Context context){
    Context mContext = context.getApplicationContext();
    mDatabase = new EventBaseHelper(context).getWritableDatabase();
}


public void updateNote(Event event){//метод обновдения строк в бд.
    String uuidString = event.getEventId().toString();
    ContentValues values = getContentValues(event);

    mDatabase.update(EventTable.NAME,values,EventTable.Cols.UUID + " = ?", new String[] {uuidString});
}

public void addEvent(Event event){
    ContentValues contentValues = getContentValues(event);
    mDatabase.insert(EventTable.NAME,null,contentValues);
}

public void deleteEvent(Event event){
    String uuid = event.getEventId().toString();
    mDatabase.delete(EventTable.NAME,EventTable.Cols.UUID + "= ?",new String[]{uuid});
}

public List<Event> getEvents(){//возвращение списка заметок
    List<Event> events = new ArrayList<>();

    EventCursorWrapper cursorWrapper = queryEvent(null,null);
    try{
        cursorWrapper.moveToFirst();
        while(!cursorWrapper.isAfterLast()){
            events.add(cursorWrapper.getEvent());
            cursorWrapper.moveToNext();
        }
    }finally {
        cursorWrapper.close();
    }
    return events;
}

public Event getEvent(UUID id){
    EventCursorWrapper cursor = queryEvent(EventTable.Cols.UUID + "= ?",
            new String[] {id.toString()}
    );

    try {
        if(cursor.getCount() == 0){
            return null;
        }

        cursor.moveToFirst();
        return cursor.getEvent();
    }finally {
        cursor.close();
    }
}

private static ContentValues getContentValues(Event event){
    ContentValues values = new ContentValues();
    values.put(EventTable.Cols.UUID,event.getEventId().toString());
    values.put(EventTable.Cols.TITLE,event.getTitle());
    values.put(EventTable.Cols.DESCRIPTION,event.getDescription());
    values.put(EventTable.Cols.EVENTSTART,event.getEndEvent().getTime());
    values.put(EventTable.Cols.EVENTFINISH,event.getStartEvent().getTime());

    values.put(EventTable.Cols.PEOPLE,event.getPeople());
    values.put(EventTable.Cols.PLACE,event.getPlace());

    return values;
}

private EventCursorWrapper queryEvent(String whereClause , String[] whereArgs){//запрос на получение данных
    Cursor cursor = mDatabase.query(
            EventTable.NAME,
            null,
            whereClause,
            whereArgs,
            null,
            null,
            null
    );

    return new EventCursorWrapper(cursor);
}

}`

Plaese help my.

Issue Analytics

  • State:open
  • Created 7 years ago
  • Comments:7 (1 by maintainers)

github_iconTop GitHub Comments

1reaction
empeuszcommented, Jan 30, 2018

I know it’s been 2 years, but did you find a solution ? I’m actually trying to load events from Room Persistence Library… has anyone tried it yet? Any code apreciated 👍 😃

0reactions
dragonglingcommented, Jun 10, 2021

I have an issue with this too. Solutions like above comment and this comment seem more like hacks than good use case for me. Setting adapter would be much better than MonthChangeListener

Read more comments on GitHub >

github_iconTop Results From Across the Web

How To show fetch events from database with time in ...
3 Answers. Save this answer. Show activity on this post. just a url at events attribute returning Json data from database.
Read more >
13.7.5.18 SHOW EVENTS Statement - MySQL :: Developer Zone
This statement displays information about Event Manager events, which are discussed in Section 23.4, “Using the Event Scheduler”. It requires ...
Read more >
Quickstart: Extended Events in SQL Server - Microsoft Learn
In the SSMS Object Explorer, you can right-click the target node which is under your event session node. In the context menu you...
Read more >
Events Overview - MariaDB Knowledge Base
A list of current events can be obtained with the SHOW EVENTS statement. This only shows the event name and interval - the...
Read more >
Calendar view – Notion Help Center
Calendars let you visualize how database items connect to certain dates. Use one when you want a bird's-eye view for important launch dates,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found