/** Get current saved sates of the Caldroid. Useful for handling rotation */
  public Bundle getSavedStates() {
    Bundle bundle = new Bundle();
    bundle.putInt(MONTH, month);
    bundle.putInt(YEAR, year);

    if (dialogTitle != null) {
      bundle.putString(DIALOG_TITLE, dialogTitle);
    }

    if (selectedDates != null && selectedDates.size() > 0) {
      bundle.putStringArrayList(SELECTED_DATES, CalendarHelper.convertToStringList(selectedDates));
    }

    if (disableDates != null && disableDates.size() > 0) {
      bundle.putStringArrayList(DISABLE_DATES, CalendarHelper.convertToStringList(disableDates));
    }

    if (minDateTime != null) {
      bundle.putString(MIN_DATE, minDateTime.format("YYYY-MM-DD"));
    }

    if (maxDateTime != null) {
      bundle.putString(MAX_DATE, maxDateTime.format("YYYY-MM-DD"));
    }

    bundle.putBoolean(SHOW_NAVIGATION_ARROWS, showNavigationArrows);
    bundle.putBoolean(ENABLE_SWIPE, enableSwipe);
    bundle.putInt(START_DAY_OF_WEEK, startDayOfWeek);
    bundle.putBoolean(SIX_WEEKS_IN_CALENDAR, sixWeeksInCalendar);

    return bundle;
  }
Esempio n. 2
0
 public static ArrayList<String> convertToStringList(ArrayList<DateTime> dateTimes) {
   ArrayList<String> list = new ArrayList<String>();
   for (DateTime dateTime : dateTimes) {
     list.add(dateTime.format("YYYY-MM-DD"));
   }
   return list;
 }
  public void setCalendarDateTime(DateTime dateTime) {
    month = dateTime.getMonth() + 1;
    year = dateTime.getYear();

    // Notify listener
    if (caldroidListener != null) {
      caldroidListener.onChangeMonth(month, year);
    }

    refreshView();
  }
Esempio n. 4
0
  public static Date convertDateTimeToDate(DateTime dateTime) {
    int year = dateTime.getYear();
    int datetimeMonth = dateTime.getMonth();
    int day = dateTime.getDay();

    Calendar calendar = Calendar.getInstance();
    calendar.clear();

    // datetimeMonth start at 1. Need to minus 1 to get javaMonth
    calendar.set(year, datetimeMonth - 1, day);

    return calendar.getTime();
  }
  /**
   * Select the dates from fromDate to toDate. By default the background color is holo_blue_light,
   * and the text color is black. You can customize the background by changing
   * CaldroidFragment.selectedBackgroundDrawable, and change the text color
   * CaldroidFragment.selectedTextColor before call this method. This method does not refresh view,
   * need to call refreshView()
   *
   * @param fromDate
   * @param toDate
   */
  public void setSelectedDates(Date fromDate, Date toDate) {
    // Ensure fromDate is before toDate
    if (fromDate == null || toDate == null || fromDate.after(toDate)) {
      return;
    }

    selectedDates.clear();

    DateTime fromDateTime = CalendarHelper.convertDateToDateTime(fromDate);
    DateTime toDateTime = CalendarHelper.convertDateToDateTime(toDate);

    DateTime dateTime = fromDateTime;
    while (dateTime.lt(toDateTime)) {
      selectedDates.add(dateTime);
      dateTime = dateTime.plusDays(1);
    }
    selectedDates.add(toDateTime);
  }
  /**
   * To display the week day title
   *
   * @return "SUN, MON, TUE, WED, THU, FRI, SAT"
   */
  protected ArrayList<String> getDaysOfWeek() {
    ArrayList<String> list = new ArrayList<String>();

    SimpleDateFormat fmt = new SimpleDateFormat("EEE", Locale.getDefault());

    // 17 Feb 2013 is Sunday
    DateTime sunday = new DateTime(2013, 2, 17, 0, 0, 0, 0);
    DateTime nextDay = sunday.plusDays(startDayOfWeek - SUNDAY);

    for (int i = 0; i < 7; i++) {
      Date date = CalendarHelper.convertDateTimeToDate(nextDay);
      list.add(fmt.format(date).toUpperCase());

      nextDay = nextDay.plusDays(1);
    }

    return list;
  }
 @Override
 public void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
   outState.putInt(KEY_ITEM_SELECTED, mItemSelected);
   outState.putString(KEY_WHERE_CLAUSE, getWhereClause());
   if (mDateFrom != null) {
     //            outState.putSerializable(KEY_FROM_DATE, mDateFrom);
     outState.putString(KEY_FROM_DATE, mDateFrom.toString());
   }
   if (mDateTo != null) outState.putSerializable(KEY_TO_DATE, mDateTo);
 }
    public void refreshAdapters(int position) {
      // Get adapters to refresh
      CaldroidGridAdapter currentAdapter = caldroidGridAdapters.get(getCurrent(position));
      CaldroidGridAdapter prevAdapter = caldroidGridAdapters.get(getPrevious(position));
      CaldroidGridAdapter nextAdapter = caldroidGridAdapters.get(getNext(position));

      if (position == currentPage) {
        // Refresh current adapter

        currentAdapter.setAdapterDateTime(currentDateTime);
        currentAdapter.notifyDataSetChanged();

        // Refresh previous adapter
        prevAdapter.setAdapterDateTime(
            currentDateTime.minus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay));
        prevAdapter.notifyDataSetChanged();

        // Refresh next adapter
        nextAdapter.setAdapterDateTime(
            currentDateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay));
        nextAdapter.notifyDataSetChanged();
      }
      // Detect if swipe right or swipe left
      // Swipe right
      else if (position > currentPage) {
        // Update current date time to next month
        currentDateTime = currentDateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);

        // Refresh the adapter of next gridview
        nextAdapter.setAdapterDateTime(
            currentDateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay));
        nextAdapter.notifyDataSetChanged();

      }
      // Swipe left
      else {
        // Update current date time to previous month
        currentDateTime = currentDateTime.minus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);

        // Refresh the adapter of previous gridview
        prevAdapter.setAdapterDateTime(
            currentDateTime.minus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay));
        prevAdapter.notifyDataSetChanged();
      }

      // Update current page
      currentPage = position;
    }
  /**
   * Move calendar to specified dateTime, with animation
   *
   * @param dateTime
   */
  public void moveToDateTime(DateTime dateTime) {

    DateTime firstOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
    DateTime lastOfMonth = firstOfMonth.getEndOfMonth();

    // To create a swipe effect
    // Do nothing if the dateTime is in current month

    // Calendar swipe left when dateTime is in the past
    if (dateTime.lt(firstOfMonth)) {
      // Get next month of dateTime. When swipe left, month will
      // decrease
      DateTime firstDayNextMonth = dateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);

      // Refresh adapters
      pageChangeListener.setCurrentDateTime(firstDayNextMonth);
      int currentItem = dateViewPager.getCurrentItem();
      pageChangeListener.refreshAdapters(currentItem);

      // Swipe left
      dateViewPager.setCurrentItem(currentItem - 1);
    }

    // Calendar swipe right when dateTime is in the future
    else if (dateTime.gt(lastOfMonth)) {
      // Get last month of dateTime. When swipe right, the month will
      // increase
      DateTime firstDayLastMonth =
          dateTime.minus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);

      // Refresh adapters
      pageChangeListener.setCurrentDateTime(firstDayLastMonth);
      int currentItem = dateViewPager.getCurrentItem();
      pageChangeListener.refreshAdapters(currentItem);

      // Swipe right
      dateViewPager.setCurrentItem(currentItem + 1);
    }
  }
Esempio n. 10
0
  /**
   * Retrieve all the dates for a given calendar month Include previous month, current month and
   * next month.
   *
   * @param month
   * @param year
   * @param startDayOfWeek : calendar can start from customized date instead of Sunday
   * @return
   */
  public static ArrayList<DateTime> getFullWeeks(
      int month, int year, int startDayOfWeek, boolean sixWeeksInCalendar) {
    ArrayList<DateTime> datetimeList = new ArrayList<DateTime>();

    DateTime firstDateOfMonth = new DateTime(year, month, 1, 0, 0, 0, 0);
    DateTime lastDateOfMonth = firstDateOfMonth.plusDays(firstDateOfMonth.getNumDaysInMonth() - 1);

    // Add dates of first week from previous month
    int weekdayOfFirstDate = firstDateOfMonth.getWeekDay();

    // If weekdayOfFirstDate smaller than startDayOfWeek
    // For e.g: weekdayFirstDate is Monday, startDayOfWeek is Tuesday
    // increase the weekday of FirstDate because it's in the future
    if (weekdayOfFirstDate < startDayOfWeek) {
      weekdayOfFirstDate += 7;
    }

    while (weekdayOfFirstDate > 0) {
      DateTime dateTime = firstDateOfMonth.minusDays(weekdayOfFirstDate - startDayOfWeek);
      if (!dateTime.lt(firstDateOfMonth)) {
        break;
      }

      datetimeList.add(dateTime);
      weekdayOfFirstDate--;
    }

    // Add dates of current month
    for (int i = 0; i < lastDateOfMonth.getDay(); i++) {
      datetimeList.add(firstDateOfMonth.plusDays(i));
    }

    // Add dates of last week from next month
    int endDayOfWeek = startDayOfWeek - 1;

    if (endDayOfWeek == 0) {
      endDayOfWeek = 7;
    }

    if (lastDateOfMonth.getWeekDay() != endDayOfWeek) {
      int i = 1;
      while (true) {
        DateTime nextDay = lastDateOfMonth.plusDays(i);
        datetimeList.add(nextDay);
        i++;
        if (nextDay.getWeekDay() == endDayOfWeek) {
          break;
        }
      }
    }

    // Add more weeks to fill remaining rows
    if (sixWeeksInCalendar) {
      int size = datetimeList.size();
      int row = size / 7;
      int numOfDays = (6 - row) * 7;
      DateTime lastDateTime = datetimeList.get(size - 1);
      for (int i = 1; i <= numOfDays; i++) {
        DateTime nextDateTime = lastDateTime.plusDays(i);
        datetimeList.add(nextDateTime);
      }
    }

    return datetimeList;
  }
Esempio n. 11
0
  public static void rebuildStats(Context context, String localId) {
    Realm realm = Realm.getInstance(Migration.getConfig(context));

    RealmResults<TrackStats> statsRes =
        realm.where(TrackStats.class).equalTo("local_id", localId).findAll();

    if (!statsRes.isEmpty()) {
      /*
      Log.d(TAG, "hi5");
      Log.d(TAG, "==================");
      Log.d(TAG, "track.getTitle(): " + track.getTitle());
      Log.d(TAG, "track.getCompletedCount(): " + track.getCompletedCount());
      Log.d(TAG, "track.getSkippedCount(): " + track.getSkippedCount());
      Log.d(TAG, "track.getLikedCount(): " + track.getLikedCount());
      Log.d(TAG, "track.getDislikedCount(): " + track.getDislikedCount());

      res.where().equalTo("type", TrackStats.SONG_SELECTED) //TODO not implemented yet
       */

      int completedCount = 0;
      int skippedCount = 0;
      int likedCount = 0;
      int dislikedCount = 0;
      int halfPlayedCount = 0;
      int selectedCount = 0;

      for (TrackStats ts : statsRes) {
        switch (ts.getType()) {
          case TrackStats.SONG_COMPLETED:
            completedCount++;
            break;
          case TrackStats.SONG_HALF_PLAYED:
            halfPlayedCount++;
            break;
          case TrackStats.SONG_SELECTED:
            selectedCount++;
            break;
          case TrackStats.SONG_SKIPPED:
            skippedCount++;
            break;
          case TrackStats.SONG_LIKED:
            likedCount++;
            break;
          case TrackStats.SONG_DISLIKED:
            dislikedCount++;
            break;
        }
      }

      Track track = realm.where(Track.class).equalTo("local_id", localId).findFirst();

      realm.beginTransaction();

      track.setCompletedCount(completedCount);
      track.setHalfPlayedCount(halfPlayedCount);
      track.setSelectedCount(selectedCount);

      track.setSkippedCount(skippedCount);

      track.setLikedCount(likedCount);
      track.setDislikedCount(dislikedCount);

      track.setStatsUpdatedAt(DateTime.now(Calendar.getInstance().getTimeZone()).toString());

      realm.commitTransaction();
    }
  }
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    // todo: replace this complex way of querying and find the start/end dates for
    // ViewMobileData.Date.
    CalendarUtils calendar = new CalendarUtils();

    //        int currentMonth = Calendar.getInstance().get(Calendar.MONTH) + 1;
    //        int currentYear = Calendar.getInstance().get(Calendar.YEAR);
    switch (item.getItemId()) {
      case R.id.menu_current_month:
        //                whereClause = ViewMobileData.Month + "=" + Integer.toString(currentMonth)
        // + " AND " +
        //                    ViewMobileData.Year + "=" + Integer.toString(currentYear);
        //                DateTime startDate = DateTime.today(TimeZone.getDefault());

        //                mDateFrom =
        // calendar.setFirstDayOfMonth().setTimeToBeginningOfDay().getTime();
        mDateFrom = DateTimeUtils.today().getStartOfMonth();
        mDateTo = calendar.setLastDayOfMonth().setTimeToEndOfDay().getTime();
        break;

      case R.id.menu_last_month:
        //                if (currentMonth == 1) {
        //                    whereClause = ViewMobileData.Month + "=" + Integer.toString(12) + "
        // AND " + ViewMobileData.Year + "=" + Integer.toString(currentYear - 1);
        //                } else {
        //                    whereClause = ViewMobileData.Month + "=" +
        // Integer.toString(currentMonth - 1) + " AND " + ViewMobileData.Year + "=" +
        // Integer.toString(currentYear);
        //                }
        //                Calendar dateFrom =
        // calendar.setNow().addMonth(-1).setFirstDayOfMonth().setTimeToBeginningOfDay().getTime();
        Calendar dateFrom =
            calendar
                .setNow()
                .addMonth(-1)
                .setFirstDayOfMonth()
                .setTimeToBeginningOfDay()
                .getCalendar();
        mDateFrom = DateTimeUtils.from(dateFrom);
        mDateTo = calendar.setLastDayOfMonth().setTimeToEndOfDay().getTime();
        break;
      case R.id.menu_last_30_days:
        //                whereClause = "(julianday(date('now')) - julianday(" + ViewMobileData.Date
        // + ") <= 30)";
        dateFrom = calendar.setNow().addDays(-30).setTimeToBeginningOfDay().getCalendar();
        mDateFrom = DateTimeUtils.from(dateFrom);
        mDateTo = calendar.setNow().setTimeToEndOfDay().getTime();
        break;
      case R.id.menu_current_year:
        //                whereClause = ViewMobileData.Year + "=" + Integer.toString(currentYear);
        dateFrom = calendar.setNow().setMonth(Calendar.JANUARY).setFirstDayOfMonth().getCalendar();
        mDateFrom = DateTimeUtils.from(dateFrom);
        mDateTo = calendar.setMonth(Calendar.DECEMBER).setLastDayOfMonth().getTime();
        break;
      case R.id.menu_last_year:
        //                whereClause = ViewMobileData.Year + "=" + Integer.toString(currentYear -
        // 1);
        dateFrom =
            calendar
                .setNow()
                .addYear(-1)
                .setMonth(Calendar.JANUARY)
                .setFirstDayOfMonth()
                .getCalendar();
        mDateFrom = DateTimeUtils.from(dateFrom);
        mDateTo = calendar.setMonth(Calendar.DECEMBER).setLastDayOfMonth().getTime();
        break;
      case R.id.menu_all_time:
        mDateFrom = null;
        mDateTo = null;
        break;
      case R.id.menu_custom_dates:
        // check item
        item.setChecked(true);
        mItemSelected = item.getItemId();
        // show dialog
        showDialogCustomDates();
        return true;
        //                break;
      default:
        return super.onOptionsItemSelected(item);
    }

    String whereClause = null;
    if (mDateFrom != null && mDateTo != null) {
      // todo: mDateFrom.format(Constants.ISO_DATE_FORMAT) ?
      whereClause =
          ViewMobileData.Date
              + " >= '"
              + mDateFrom.toString()
              + "' AND "
              + ViewMobileData.Date
              + " <= '"
              + DateUtils.getIsoStringDate(mDateTo)
              + "'";
    }

    // check item
    item.setChecked(true);
    mItemSelected = item.getItemId();

    // compose bundle
    Bundle args = new Bundle();
    args.putString(KEY_WHERE_CLAUSE, whereClause);

    // starts loader
    startLoader(args);

    return true;
  }
  /**
   * Retrieve initial arguments to the fragment Data can include: month, year, dialogTitle,
   * showNavigationArrows,(String) disableDates, selectedDates, minDate, maxDate
   */
  protected void retrieveInitialArgs() {
    // Get arguments
    Bundle args = getArguments();
    if (args != null) {
      // Get month, year
      month = args.getInt(MONTH, -1);
      year = args.getInt(YEAR, -1);
      dialogTitle = args.getString(DIALOG_TITLE);
      Dialog dialog = getDialog();
      if (dialog != null) {
        if (dialogTitle != null) {
          dialog.setTitle(dialogTitle);
        } else {
          // Don't display title bar if user did not supply
          // dialogTitle
          dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
      }

      // Get start day of Week. Default calendar first column is SUNDAY
      startDayOfWeek = args.getInt(START_DAY_OF_WEEK, 1);
      if (startDayOfWeek > 7) {
        startDayOfWeek = startDayOfWeek % 7;
      }

      // Should show arrow
      showNavigationArrows = args.getBoolean(SHOW_NAVIGATION_ARROWS, true);

      // Should enable swipe to change month
      enableSwipe = args.getBoolean(ENABLE_SWIPE, true);

      // Get sixWeeksInCalendar
      sixWeeksInCalendar = args.getBoolean(SIX_WEEKS_IN_CALENDAR, true);

      // Get clickable setting
      enableClickOnDisabledDates = args.getBoolean(ENABLE_CLICK_ON_DISABLED_DATES, false);

      // Get disable dates
      ArrayList<String> disableDateStrings = args.getStringArrayList(DISABLE_DATES);
      if (disableDateStrings != null && disableDateStrings.size() > 0) {
        disableDates.clear();
        for (String dateString : disableDateStrings) {
          DateTime dt = CalendarHelper.getDateTimeFromString(dateString, "yyyy-MM-dd");
          disableDates.add(dt);
        }
      }

      // Get selected dates
      ArrayList<String> selectedDateStrings = args.getStringArrayList(SELECTED_DATES);
      if (selectedDateStrings != null && selectedDateStrings.size() > 0) {
        selectedDates.clear();
        for (String dateString : selectedDateStrings) {
          DateTime dt = CalendarHelper.getDateTimeFromString(dateString, "yyyy-MM-dd");
          selectedDates.add(dt);
        }
      }

      // Get min date and max date
      String minDateTimeString = args.getString(MIN_DATE);
      if (minDateTimeString != null) {
        minDateTime = CalendarHelper.getDateTimeFromString(minDateTimeString, null);
      }

      String maxDateTimeString = args.getString(MAX_DATE);
      if (maxDateTimeString != null) {
        maxDateTime = CalendarHelper.getDateTimeFromString(maxDateTimeString, null);
      }
    }
    if (month == -1 || year == -1) {
      DateTime dateTime = DateTime.today(TimeZone.getDefault());
      month = dateTime.getMonth();
      year = dateTime.getYear();
    }
  }
  /**
   * Setup 4 pages contain date grid views. These pages are recycled to use memory efficient
   *
   * @param view
   */
  private void setupDateGridPages(View view) {
    // Get current date time
    DateTime currentDateTime = new DateTime(year, month + 1, 1, 0, 0, 0, 0);

    // Set to pageChangeListener
    pageChangeListener = new DatePageChangeListener();
    pageChangeListener.setCurrentDateTime(currentDateTime);

    // Setup adapters for the grid views
    // Current month
    CaldroidGridAdapter adapter0 =
        getNewDatesGridAdapter(currentDateTime.getMonth(), currentDateTime.getYear());

    // Setup dateInMonthsList
    dateInMonthsList = adapter0.getDatetimeList();

    // Next month
    DateTime nextDateTime = currentDateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);
    CaldroidGridAdapter adapter1 =
        getNewDatesGridAdapter(nextDateTime.getMonth(), nextDateTime.getYear());

    // Next 2 month
    DateTime next2DateTime = nextDateTime.plus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);
    CaldroidGridAdapter adapter2 =
        getNewDatesGridAdapter(next2DateTime.getMonth(), next2DateTime.getYear());

    // Previous month
    DateTime prevDateTime =
        currentDateTime.minus(0, 1, 0, 0, 0, 0, 0, DateTime.DayOverflow.LastDay);
    CaldroidGridAdapter adapter3 =
        getNewDatesGridAdapter(prevDateTime.getMonth(), prevDateTime.getYear());

    // Add to the array of adapters
    datePagerAdapters.add(adapter0);
    datePagerAdapters.add(adapter1);
    datePagerAdapters.add(adapter2);
    datePagerAdapters.add(adapter3);

    // Set adapters to the pageChangeListener so it can refresh the adapter
    // when page change
    pageChangeListener.setCaldroidGridAdapters(datePagerAdapters);

    // Setup InfiniteViewPager and InfinitePagerAdapter. The
    // InfinitePagerAdapter is responsible
    // for reuse the fragments
    dateViewPager = (InfiniteViewPager) view.findViewById(R.id.months_infinite_pager);

    // Set enable swipe
    dateViewPager.setEnabled(enableSwipe);

    // Set if viewpager wrap around particular month or all months (6 rows)
    dateViewPager.setSixWeeksInCalendar(sixWeeksInCalendar);

    // Set the numberOfDaysInMonth to dateViewPager so it can calculate the
    // height correctly
    dateViewPager.setDatesInMonth(dateInMonthsList);

    // MonthPagerAdapter actually provides 4 real fragments. The
    // InfinitePagerAdapter only recycles fragment provided by this
    // MonthPagerAdapter
    final MonthPagerAdapter pagerAdapter = new MonthPagerAdapter(getChildFragmentManager());

    // Provide initial data to the fragments, before they are attached to
    // view.
    fragments = pagerAdapter.getFragments();
    for (int i = 0; i < NUMBER_OF_PAGES; i++) {
      DateGridFragment dateGridFragment = fragments.get(i);
      CaldroidGridAdapter adapter = datePagerAdapters.get(i);
      dateGridFragment.setGridAdapter(adapter);
      dateGridFragment.setOnItemClickListener(getDateItemClickListener());
      dateGridFragment.setOnItemLongClickListener(getDateItemLongClickListener());
    }

    // Setup InfinitePagerAdapter to wrap around MonthPagerAdapter
    InfinitePagerAdapter infinitePagerAdapter = new InfinitePagerAdapter(pagerAdapter);

    // Use the infinitePagerAdapter to provide data for dateViewPager
    dateViewPager.setAdapter(infinitePagerAdapter);

    // Setup pageChangeListener
    dateViewPager.setOnPageChangeListener(pageChangeListener);
  }