alamkanak / Android-Week-View

Android Week View is an android library to display calendars (week view or day view) within the app. It supports custom styling.
Apache License 2.0
3.43k stars 1.23k forks source link

How display events from database #374

Open citizen2 opened 8 years ago

citizen2 commented 8 years ago

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.

entropitor commented 8 years ago

Are you sure you are returning events in your onMonthChange?

citizen2 commented 8 years ago

I think yes, but I am not a sure.

citizen2 commented 8 years ago

So, somebody know where I made a mistake?

empeusz commented 6 years ago

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 👍 :)

Hanif-abuvani commented 6 years ago

@citizen2 Can you share your database for event store and retrieval?

NaturallyAsh commented 6 years ago

I created a base fragment that extended my weekView fragment (which I made abstract). My base is where I load my events. I stored my data from my add event activity in the database and called it using a cursor I placed in my base fragment to load the event. Works for me. Check out that part of my app on my page (the entire app is very incomplete but the sqlite and saving and retrieving it works).

dragongling commented 3 years ago

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