Example usage for android.text.format Time Time

List of usage examples for android.text.format Time Time

Introduction

In this page you can find the example usage for android.text.format Time Time.

Prototype

public Time() 

Source Link

Document

Construct a Time object in the default timezone.

Usage

From source file:co.carlosjimenez.android.currencyalerts.app.sync.ForexSyncAdapter.java

/**
 * Take the String representing the complete forex in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>//  www .j  a  v  a2  s .c o m
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getForexDataFromJson(String forexJsonStr, String currencyQuery) throws JSONException {

    // Now we have a String representing the complete forex in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_RESULT = "results";
    final String OWM_RATE_FROM = "fr";
    final String OWM_RATE_TO = "to";
    final String OWM_RATE = "val";
    String[] currencies;
    boolean alertAvailable = false;

    try {
        if (mAlertData != null && mAlertData.getCurrencyFrom() != null && mAlertData.getCurrencyTo() != null) {
            alertAvailable = true;
        }

        JSONObject forexJson = new JSONObject(forexJsonStr);

        // do we have an error?
        if (!forexJson.has(OWM_RESULT)) {
            setForexStatus(getContext(), FOREX_STATUS_INVALID);
            return;
        }

        currencies = currencyQuery.split(",");

        JSONObject forexResultObject = forexJson.getJSONObject(OWM_RESULT);

        // OWM returns daily rates based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our rates.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianDate = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();
        long dateTime = dayTime.setJulianDay(julianDate);

        // Insert the new rates information into the database
        Vector<ContentValues> cVVector = new Vector<>(currencies.length);

        for (int i = 0; i < currencies.length; i++) {

            JSONObject currencyObject = forexResultObject.getJSONObject(currencies[i]);
            String rate_from = currencyObject.getString(OWM_RATE_FROM);
            String rate_to = currencyObject.getString(OWM_RATE_TO);
            double result = currencyObject.getDouble(OWM_RATE);

            ContentValues forexValues = new ContentValues();

            forexValues.put(ForexContract.RateEntry.COLUMN_RATE_FROM_KEY, rate_from);
            forexValues.put(ForexContract.RateEntry.COLUMN_RATE_TO_KEY, rate_to);
            forexValues.put(ForexContract.RateEntry.COLUMN_RATE_DATE, dateTime);
            forexValues.put(ForexContract.RateEntry.COLUMN_RATE_VALUE, result);

            if (alertAvailable && mAlertData.getCurrencyFrom().getId().equals(rate_from)
                    && mAlertData.getCurrencyTo().getId().equals(rate_to)) {
                mCurrentAlertRate = result;
            }

            cVVector.add(forexValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            getContext().getContentResolver().bulkInsert(ForexContract.RateEntry.CONTENT_URI, cvArray);

            // delete old data so we don't build up an endless history
            getContext().getContentResolver().delete(ForexContract.RateEntry.CONTENT_URI,
                    ForexContract.RateEntry.COLUMN_RATE_DATE + " <= ?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianDate - FOREX_DAYS_TO_KEEP)) });

            setForexSyncDate(getContext(), System.currentTimeMillis());
            sendSyncBroadcast(FOREX_STATUS_OK);
            checkCurrencyData();
        }

        Log.d(LOG_TAG, "ForexSyncAdapter: Sync Complete. " + cVVector.size() + " Inserted");
        setForexStatus(getContext(), FOREX_STATUS_OK);

    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        setForexStatus(getContext(), FOREX_STATUS_SERVER_INVALID);
    }
}

From source file:com.android.calendar.recurrencepicker.RecurrencePickerDialog.java

static private void copyEventRecurrenceToModel(final EventRecurrence er, RecurrenceModel model) {
    // Freq:/*from www.j  av  a  2s.  c  om*/
    switch (er.freq) {
    case EventRecurrence.DAILY:
        model.freq = RecurrenceModel.FREQ_DAILY;
        break;
    case EventRecurrence.MONTHLY:
        model.freq = RecurrenceModel.FREQ_MONTHLY;
        break;
    case EventRecurrence.YEARLY:
        model.freq = RecurrenceModel.FREQ_YEARLY;
        break;
    case EventRecurrence.WEEKLY:
        model.freq = RecurrenceModel.FREQ_WEEKLY;
        break;
    default:
        throw new IllegalStateException("freq=" + er.freq);
    }

    // Interval:
    if (er.interval > 0) {
        model.interval = er.interval;
    }

    // End:
    // End by count:
    model.endCount = er.count;
    if (model.endCount > 0) {
        model.end = RecurrenceModel.END_BY_COUNT;
    }

    // End by date:
    if (!TextUtils.isEmpty(er.until)) {
        if (model.endDate == null) {
            model.endDate = new Time();
        }

        try {
            model.endDate.parse(er.until);
        } catch (TimeFormatException e) {
            model.endDate = null;
        }

        // LIMITATION: The UI can only handle END_BY_DATE or END_BY_COUNT
        if (model.end == RecurrenceModel.END_BY_COUNT && model.endDate != null) {
            throw new IllegalStateException("freq=" + er.freq);
        }

        model.end = RecurrenceModel.END_BY_DATE;
    }

    // Weekly: repeat by day of week or Monthly: repeat by nth day of week
    // in the month
    Arrays.fill(model.weeklyByDayOfWeek, false);
    if (er.bydayCount > 0) {
        int count = 0;
        for (int i = 0; i < er.bydayCount; i++) {
            int dayOfWeek = EventRecurrence.day2TimeDay(er.byday[i]);
            model.weeklyByDayOfWeek[dayOfWeek] = true;

            if (model.freq == RecurrenceModel.FREQ_MONTHLY
                    && isSupportedMonthlyByNthDayOfWeek(er.bydayNum[i])) {
                // LIMITATION: Can handle only (one) weekDayNum in nth or
                // last and only
                // when
                // monthly
                model.monthlyByDayOfWeek = dayOfWeek;
                model.monthlyByNthDayOfWeek = er.bydayNum[i];
                model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK;
                count++;
            }
        }

        if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
            if (er.bydayCount != 1) {
                // Can't handle 1st Monday and 2nd Wed
                throw new IllegalStateException("Can handle only 1 byDayOfWeek in monthly");
            }
            if (count != 1) {
                throw new IllegalStateException("Didn't specify which nth day of week to repeat for a monthly");
            }
        }
    }

    // Monthly by day of month
    if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
        if (er.bymonthdayCount == 1) {
            if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) {
                throw new IllegalStateException("Can handle only by monthday or by nth day of week, not both");
            }
            model.monthlyByMonthDay = er.bymonthday[0];
            model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE;
        } else if (er.bymonthCount > 1) {
            // LIMITATION: Can handle only one month day
            throw new IllegalStateException("Can handle only one bymonthday");
        }
    }
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static long setUpdateAlarm(Context context, boolean initial) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent alarmintent = new Intent(context, AlarmReceiver.class);
    alarmintent.setAction(AlarmReceiver.ALARM_UPDATE);

    PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, alarmintent, 0);

    MyApp.LogDebug(LOG_TAG, "set update alarm");
    long next_fetch;
    long interval;
    Time t = new Time();
    t.setToNow();/*from w w w  . j  av  a2  s  .  co m*/
    long now = t.toMillis(true);

    if ((now >= MyApp.first_day_start) && (now < MyApp.last_day_end)) {
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        next_fetch = now + interval;
    } else if (now >= MyApp.last_day_end) {
        MyApp.LogDebug(LOG_TAG, "cancel alarm post congress");
        alarmManager.cancel(pendingintent);
        return 0;
    } else {
        interval = AlarmManager.INTERVAL_DAY;
        next_fetch = now + interval;
    }

    if ((now < MyApp.first_day_start) && ((now + AlarmManager.INTERVAL_DAY) >= MyApp.first_day_start)) {
        next_fetch = MyApp.first_day_start;
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        if (!initial) {
            MyApp.LogDebug(LOG_TAG, "update alarm to interval " + interval + ", next in " + (next_fetch - now));
            alarmManager.cancel(pendingintent);
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
        }
    }

    if (initial) {
        MyApp.LogDebug(LOG_TAG,
                "set initial alarm to interval " + interval + ", next in " + (next_fetch - now));
        alarmManager.cancel(pendingintent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
    }

    return interval;
}

From source file:me.zhang.bingo.Utility.java

/**
 * Helper method to convert the database representation of the date into something to display
 * to users.  As classy and polished a user experience as "20170701" is, we can do better.
 *
 * @param context      Context to use for resource localization
 * @param rawStartDate The date string: "20170701"
 * @return a user-friendly representation of the date.
 *//*from  w  ww.jav a2 s  . com*/
public static String getFriendlyDayString(Context context, String rawStartDate) {
    // The day string for forecast uses the following logic:
    // For today: "Today, July 1"
    // For yesterday:  "Yesterday"
    // For all days before that: "Wed Jun 28"

    Time time = new Time();
    time.setToNow();
    long currentTime = System.currentTimeMillis();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, getChoosedLocale(context));
    long dateInMillis = 0;
    try {
        dateInMillis = sdf.parse(rawStartDate).getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    int julianDay = Time.getJulianDay(dateInMillis, time.gmtoff);
    int currentJulianDay = Time.getJulianDay(currentTime, time.gmtoff);

    if (julianDay == currentJulianDay) { // Today
        String today = context.getString(R.string.today);
        return context.getString(R.string.format_full_friendly_date, today,
                getFormattedMonthDay(context, dateInMillis));
    } else if (julianDay == currentJulianDay - 1) { // Yesterday
        return context.getString(R.string.yesterday);
    } else {
        // Otherwise, use the form "Jun 28"
        SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("MMM d", getChoosedLocale(context));
        return shortenedDateFormat.format(dateInMillis);
    }
}

From source file:com.jogden.spunkycharts.pricebyvolumechart.PriceByVolumeChartFragmentAdapter.java

private Time _truncateTime(Time t, long msInterval, boolean ignoreDST, boolean inPlace) {
    long ms = t.toMillis(ignoreDST);
    ms /= msInterval;//from  ww w.java 2s  .  c om
    ms *= msInterval;
    if (inPlace) {
        t.set(ms);
        return t;
    } else {
        Time nTime = new Time();
        nTime.set(ms);
        return nTime;
    }
}

From source file:com.readystatesoftware.ghostlog.LogService.java

@Override
public void onLogShare() {
    StringBuffer sb = new StringBuffer();
    for (LogLine line : mLogBufferFiltered) {
        sb.append(line.getRaw());//from ww  w.  j av a 2  s. c  o  m
        sb.append("\n");
    }
    Time now = new Time();
    now.setToNow();
    String ts = now.format3339(false);

    Intent shareIntent = new Intent(Intent.ACTION_SEND);
    shareIntent.setType("text/plain");
    shareIntent.putExtra(Intent.EXTRA_TEXT, sb.toString());
    shareIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.share_subject) + " " + ts);
    shareIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(shareIntent);
}

From source file:org.dmfs.tasks.notification.NotificationUpdaterService.java

private static String makePinNotificationContentText(Context context, ContentSet task) {
    boolean isAllDay = TaskFieldAdapters.ALLDAY.get(task);
    Time now = new Time();
    now.setToNow();/*from w  ww. j  a  v a2 s .c o  m*/
    now.minute--;
    Time start = TaskFieldAdapters.DTSTART.get(task);
    Time due = TaskFieldAdapters.DUE.get(task);

    if (start != null && start.toMillis(true) > 0 && (now.before(start) || due == null)) {
        start.allDay = isAllDay;
        String startString = context.getString(R.string.notification_task_start_date,
                NotificationActionUtils.formatTime(context, start));
        return startString;
    }

    if (due != null && due.toMillis(true) > 0) {
        due.allDay = isAllDay;
        String dueString = context.getString(R.string.notification_task_due_date,
                NotificationActionUtils.formatTime(context, due));
        return dueString;
    }

    String description = TaskFieldAdapters.DESCRIPTION.get(task);
    if (description != null) {
        description = description.replaceAll("\\[\\s?\\]", "?").replaceAll("\\[[xX]\\]", "");

    }
    return description;
}

From source file:com.katamaditya.apps.weather4u.weathersync.Weather4USyncAdapter.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 * <p/>/* ww w .j  a  va2 s.c o m*/
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us.
 */
private void getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException {

    // Now we have a String representing the complete forecast in JSON Format.
    // Fortunately parsing is easy:  constructor takes the JSON string and converts it
    // into an Object hierarchy for us.

    // These are the names of the JSON objects that need to be extracted.

    // Location information
    final String OWM_CITY = "city";
    final String OWM_CITY_NAME = "name";
    final String OWM_COORD = "coord";

    // Location coordinate
    final String OWM_LATITUDE = "lat";
    final String OWM_LONGITUDE = "lon";

    // Weather information.  Each day's forecast info is an element of the "list" array.
    final String OWM_LIST = "list";

    final String OWM_PRESSURE = "pressure";
    final String OWM_HUMIDITY = "humidity";
    final String OWM_WINDSPEED = "speed";
    final String OWM_WIND_DIRECTION = "deg";

    // All temperatures are children of the "temp" object.
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";

    final String OWM_WEATHER = "weather";
    final String OWM_DESCRIPTION = "main";
    final String OWM_WEATHER_ID = "id";

    try {
        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

        JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY);
        String cityName = cityJson.getString(OWM_CITY_NAME);

        JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD);
        double cityLatitude = cityCoord.getDouble(OWM_LATITUDE);
        double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE);

        long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude);

        // Insert the new weather information into the database
        Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length());

        // OWM returns daily forecasts based upon the local time of the city that is being
        // asked for, which means that we need to know the GMT offset to translate this data
        // properly.

        // Since this data is also sent in-order and the first day is always the
        // current day, we're going to take advantage of that to get a nice
        // normalized UTC date for all of our weather.

        Time dayTime = new Time();
        dayTime.setToNow();

        // we start at the day returned by local time. Otherwise this is a mess.
        int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);

        // now we work exclusively in UTC
        dayTime = new Time();

        for (int i = 0; i < weatherArray.length(); i++) {
            // These are the values that will be collected.
            long dateTime;
            double pressure;
            int humidity;
            double windSpeed;
            double windDirection;

            double high;
            double low;

            String description;
            int weatherId;

            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);

            // Cheating to convert this to UTC time, which is what we want anyhow
            dateTime = dayTime.setJulianDay(julianStartDay + i);

            pressure = dayForecast.getDouble(OWM_PRESSURE);
            humidity = dayForecast.getInt(OWM_HUMIDITY);
            windSpeed = dayForecast.getDouble(OWM_WINDSPEED);
            windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION);

            // Description is in a child array called "weather", which is 1 element long.
            // That element also contains a weather code.
            JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
            description = weatherObject.getString(OWM_DESCRIPTION);
            weatherId = weatherObject.getInt(OWM_WEATHER_ID);

            // Temperatures are in a child object called "temp".  Try not to name variables
            // "temp" when working with temperature.  It confuses everybody.
            JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
            high = temperatureObject.getDouble(OWM_MAX);
            low = temperatureObject.getDouble(OWM_MIN);

            ContentValues weatherValues = new ContentValues();

            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherContract.WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            getContext().getContentResolver().bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, cvArray);

            // delete old data so we don't build up an endless history
            getContext().getContentResolver().delete(WeatherContract.WeatherEntry.CONTENT_URI,
                    WeatherContract.WeatherEntry.COLUMN_DATE + " <= ?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

From source file:mtmo.test.mediadrm.MainActivity.java

private void setupDrmProcessButton(final int appMode) {
    final Button btnRegistration = (Button) findViewById(R.id.btn_registration);
    final Button btnSaveLicense = (Button) findViewById(R.id.btn_license);
    final Button btnDeregistration = (Button) findViewById(R.id.btn_deregistration);
    final Button btnCheckRights = (Button) findViewById(R.id.btn_check_rights);
    final Button btnRemoveRights = (Button) findViewById(R.id.btn_remove_rights);
    final Button btnStatus = (Button) findViewById(R.id.btn_check_regist);

    if (btnRegistration != null) {
        btnRegistration.setOnClickListener(new OnClickListener() {
            @Override//ww w .j  a va 2 s  . c  om
            public void onClick(View v) {
                mLogger.enter("requeseted registration...");

                final TaskInfo taskInfo = new TaskInfo(TaskType.REGISTRATION, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnSaveLicense != null) {
        btnSaveLicense.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted getting License...");
                final TaskInfo taskInfo = new TaskInfo(TaskType.LICENSE, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnDeregistration != null) {
        btnDeregistration.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted deregistration...");
                final TaskInfo taskInfo = new TaskInfo(TaskType.DEREGISTRATION, mAccountId, mServiceId,
                        mCurrentATKNFilePath);
                mHandler.post(new TaskStarter(taskInfo));
            }
        });
    }
    if (btnCheckRights != null) {
        btnCheckRights.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted check License...");
                TextView log = (TextView) findViewById(R.id.log);
                byte[] sessionId = null;
                MediaDrm mediaDrm = null;
                byte[] contentData = null;
                log.setText("");

                try {
                    mediaDrm = new MediaDrm(Constants.MBB_UUID);
                    sessionId = mediaDrm.openSession();

                    switch (appMode) {
                    case Constants.APP_MODE_ABS:
                        ABSContentInfo absContentInfo = getABSContentInfo();
                        contentData = Utils.readPsshDataFromFile(true);
                        mediaDrm.restoreKeys(sessionId,
                                InitData.getPSSHTableForAndroid(contentData, absContentInfo.getVideoKid()));
                        break;
                    case Constants.APP_MODE_OFFLINE:
                        contentData = Utils.readIPMPDataFromFile(true);
                        mediaDrm.restoreKeys(sessionId, InitData.getIPMPTableForAndroid(contentData));
                        break;
                    default:
                        Toast.makeText(mContext, "Unknown App Mode", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    HashMap<String, String> infoMap = mediaDrm.queryKeyStatus(sessionId);

                    if (infoMap != null && infoMap.size() > 0) {
                        StringBuilder sb = new StringBuilder();
                        Iterator<String> iterator = infoMap.keySet().iterator();
                        log.setText("");
                        Time time = new Time();
                        while (iterator.hasNext()) {
                            String name = iterator.next();
                            time.set(Long.valueOf(infoMap.get(name)));
                            mLogger.d("\t" + name + " = " + infoMap.get(name) + " [" + time.format2445() + "]");
                            sb.append(
                                    "\n\t" + name + " = " + infoMap.get(name) + " [" + time.format2445() + "]");
                        }
                        log.append(sb);
                    }
                    mediaDrm.closeSession(sessionId);
                    sessionId = null;
                    Toast.makeText(MainActivity.this, "queryKeyStatus finished", Toast.LENGTH_LONG).show();
                    return;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (UnsupportedSchemeException e) {
                    e.printStackTrace();
                } catch (NotProvisionedException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                mediaDrm.closeSession(sessionId);
                sessionId = null;
                Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
            }
        });
    }
    if (btnRemoveRights != null) {
        btnRemoveRights.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.d("requeseted removing License...");
                Toast.makeText(MainActivity.this, "Not implementation", Toast.LENGTH_LONG).show();
            }
        });
    }
    if (btnStatus != null) {
        btnStatus.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mLogger.enter("Check registration Status...");

                RequestParser parser = null;
                MediaDrm mediaDrm = null;
                byte[] sessionid = null;
                HashMap<String, String> optionalParameters = null;
                try {
                    mediaDrm = new MediaDrm(Constants.MBB_UUID);
                    sessionid = mediaDrm.openSession();
                    KeyRequest keyRequest = mediaDrm.getKeyRequest(sessionid,
                            InitData.getPropertyTableForAndroid(Constants.QUERY_NAME_REGISTERED_STATE,
                                    Utils.accountIdToMarlinFormat(mAccountId), mServiceId),
                            Constants.REQUEST_MIMETYPE_QUERY_PROPERTY, MediaDrm.KEY_TYPE_OFFLINE,
                            optionalParameters);
                    parser = new RequestParser(keyRequest.getData());

                    if (parser.parse()) {
                        Toast.makeText(MainActivity.this, parser.getProperty(), Toast.LENGTH_LONG).show();
                    } else {
                        Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
                    }
                    return;
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (UnsupportedSchemeException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (NotProvisionedException e) {
                    e.printStackTrace();
                }
                Toast.makeText(MainActivity.this, "Failure", Toast.LENGTH_LONG).show();
            }
        });
    }
}

From source file:com.codetroopers.betterpickers.recurrencepicker.RecurrencePickerDialogFragment.java

static private void copyEventRecurrenceToModel(final EventRecurrence er, RecurrenceModel model) {
    // Freq:/*from   www. j a va2s . c om*/
    switch (er.freq) {
    case EventRecurrence.HOURLY:
        model.freq = RecurrenceModel.FREQ_HOURLY;
        break;
    case EventRecurrence.DAILY:
        model.freq = RecurrenceModel.FREQ_DAILY;
        break;
    case EventRecurrence.MONTHLY:
        model.freq = RecurrenceModel.FREQ_MONTHLY;
        break;
    case EventRecurrence.YEARLY:
        model.freq = RecurrenceModel.FREQ_YEARLY;
        break;
    case EventRecurrence.WEEKLY:
        model.freq = RecurrenceModel.FREQ_WEEKLY;
        break;
    default:
        throw new IllegalStateException("freq=" + er.freq);
    }

    // Interval:
    if (er.interval > 0) {
        model.interval = er.interval;
    }

    // End:
    // End by count:
    model.endCount = er.count;
    if (model.endCount > 0) {
        model.end = RecurrenceModel.END_BY_COUNT;
    }

    // End by date:
    if (!TextUtils.isEmpty(er.until)) {
        if (model.endDate == null) {
            model.endDate = new Time();
        }

        try {
            model.endDate.parse(er.until);
        } catch (TimeFormatException e) {
            model.endDate = null;
        }

        // LIMITATION: The UI can only handle END_BY_DATE or END_BY_COUNT
        if (model.end == RecurrenceModel.END_BY_COUNT && model.endDate != null) {
            throw new IllegalStateException("freq=" + er.freq);
        }

        model.end = RecurrenceModel.END_BY_DATE;
    }

    // Weekly: repeat by day of week or Monthly: repeat by nth day of week
    // in the month
    Arrays.fill(model.weeklyByDayOfWeek, false);
    if (er.bydayCount > 0) {
        int count = 0;
        for (int i = 0; i < er.bydayCount; i++) {
            int dayOfWeek = EventRecurrence.day2TimeDay(er.byday[i]);
            model.weeklyByDayOfWeek[dayOfWeek] = true;

            if (model.freq == RecurrenceModel.FREQ_MONTHLY
                    && isSupportedMonthlyByNthDayOfWeek(er.bydayNum[i])) {
                // LIMITATION: Can handle only (one) weekDayNum in nth or last and only
                // when
                // monthly
                model.monthlyByDayOfWeek = dayOfWeek;
                model.monthlyByNthDayOfWeek = er.bydayNum[i];
                model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK;
                count++;
            }
        }

        if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
            if (er.bydayCount != 1) {
                // Can't handle 1st Monday and 2nd Wed
                throw new IllegalStateException("Can handle only 1 byDayOfWeek in monthly");
            }
            if (count != 1) {
                throw new IllegalStateException("Didn't specify which nth day of week to repeat for a monthly");
            }
        }
    }

    // Monthly by day of month
    if (model.freq == RecurrenceModel.FREQ_MONTHLY) {
        if (er.bymonthdayCount == 1) {
            if (model.monthlyRepeat == RecurrenceModel.MONTHLY_BY_NTH_DAY_OF_WEEK) {
                throw new IllegalStateException("Can handle only by monthday or by nth day of week, not both");
            }
            model.monthlyByMonthDay = er.bymonthday[0];
            model.monthlyRepeat = RecurrenceModel.MONTHLY_BY_DATE;
        } else if (er.bymonthCount > 1) {
            // LIMITATION: Can handle only one month day
            throw new IllegalStateException("Can handle only one bymonthday");
        }
    }
}