Java Examples for android.text.format.DateFormat

The following java examples will help you to understand the usage of android.text.format.DateFormat. These source code samples are taken from different open source projects.

Example 1
Project: aceim-master  File: Chat.java View source code
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    MainActivity a = getMainActivity();
    switch(item.getItemId()) {
        case R.id.menuitem_close:
            removeMe();
            break;
        case R.id.menuitem_history:
            Page.getHistoryPage(a.getScreen(), mBuddy);
            break;
        case R.id.menuitem_send_file:
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("file/*");
            int requestCode = ServiceUtils.getRequestCodeForActivity(mBuddy.getEntityId().hashCode());
            //Android alters request code if startActivityForResult being started from a Fragment. We don't need that, so starting from an activity
            try {
                a.startActivityForResult(intent, requestCode);
            } catch (Exception e) {
                intent.setType("image/*");
                try {
                    a.startActivityForResult(intent, requestCode);
                } catch (Exception e1) {
                    ViewUtils.showAlertToast(a, android.R.drawable.ic_dialog_alert, R.string.no_app_for_picking_file_found, null);
                }
            }
            break;
        case R.id.menuitem_send_photo:
            intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            mAwaitingUri = Uri.fromFile(Utils.createLocalFileForReceiving(android.text.format.DateFormat.getLongDateFormat(a).format(Calendar.getInstance().getTime()) + ".jpg", mBuddy, System.currentTimeMillis()));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mAwaitingUri);
            requestCode = ServiceUtils.getRequestCodeForActivity(mBuddy.getEntityId().hashCode());
            try {
                a.startActivityForResult(intent, requestCode);
            } catch (Exception e) {
                ViewUtils.showAlertToast(a, android.R.drawable.ic_dialog_alert, R.string.no_app_for_picking_file_found, null);
            }
            break;
        case R.id.menuitem_send_location:
            try {
                a.getCoreService().sendLocation(mBuddy);
            } catch (RemoteException e) {
                a.onRemoteException(e);
            }
            break;
        case R.id.menuitem_join_chat:
            try {
                a.getCoreService().joinChat(mBuddy.getServiceId(), mBuddy.getProtocolUid());
            } catch (RemoteException e) {
                a.onRemoteException(e);
            }
            break;
        case R.id.menuitem_leave_chat:
            try {
                a.getCoreService().leaveChat(mBuddy.getServiceId(), mBuddy.getProtocolUid());
            } catch (RemoteException e) {
                a.onRemoteException(e);
            }
        case R.id.menuitem_participants:
            int v = mChatBuddies.getVisibility() == View.VISIBLE ? View.GONE : View.VISIBLE;
            mChatBuddies.setVisibility(v);
            break;
    }
    return false;
}
Example 2
Project: konkamusic-master  File: KkDigitalClock.java View source code
@Override
protected void onAttachedToWindow() {
    // TODO Auto-generated method stub
    //		super.onAttachedToWindow();
    mTickerStopped = false;
    super.onAttachedToWindow();
    mHandler = new Handler();
    /**
	         * requests a tick on the next hard-second boundary
	         */
    mTicker = new Runnable() {

        @Override
        public void run() {
            if (mTickerStopped)
                return;
            mCalendar.setTimeInMillis(System.currentTimeMillis());
            setText(DateFormat.format(mFormat, mCalendar));
            invalidate();
            long now = SystemClock.uptimeMillis();
            long next = now + (1000 - now % 1000);
            mHandler.postAtTime(mTicker, next);
        }
    };
    mTicker.run();
}
Example 3
Project: android-15-master  File: Clock.java View source code
private final CharSequence getSmallTime() {
    Context context = getContext();
    boolean b24 = DateFormat.is24HourFormat(context);
    int res;
    if (b24) {
        res = R.string.twenty_four_hour_time_format;
    } else {
        res = R.string.twelve_hour_time_format;
    }
    final char MAGIC1 = '';
    final char MAGIC2 = '';
    SimpleDateFormat sdf;
    String format = context.getString(res);
    if (!format.equals(mClockFormatString)) {
        /*
             * Search for an unquoted "a" in the format string, so we can
             * add dummy characters around it to let us find it again after
             * formatting and change its size.
             */
        if (AM_PM_STYLE != AM_PM_STYLE_NORMAL) {
            int a = -1;
            boolean quoted = false;
            for (int i = 0; i < format.length(); i++) {
                char c = format.charAt(i);
                if (c == '\'') {
                    quoted = !quoted;
                }
                if (!quoted && c == 'a') {
                    a = i;
                    break;
                }
            }
            if (a >= 0) {
                // Move a back so any whitespace before AM/PM is also in the alternate size.
                final int b = a;
                while (a > 0 && Character.isWhitespace(format.charAt(a - 1))) {
                    a--;
                }
                format = format.substring(0, a) + MAGIC1 + format.substring(a, b) + "a" + MAGIC2 + format.substring(b + 1);
            }
        }
        mClockFormat = sdf = new SimpleDateFormat(format);
        mClockFormatString = format;
    } else {
        sdf = mClockFormat;
    }
    String result = sdf.format(mCalendar.getTime());
    if (AM_PM_STYLE != AM_PM_STYLE_NORMAL) {
        int magic1 = result.indexOf(MAGIC1);
        int magic2 = result.indexOf(MAGIC2);
        if (magic1 >= 0 && magic2 > magic1) {
            SpannableStringBuilder formatted = new SpannableStringBuilder(result);
            if (AM_PM_STYLE == AM_PM_STYLE_GONE) {
                formatted.delete(magic1, magic2 + 1);
            } else {
                if (AM_PM_STYLE == AM_PM_STYLE_SMALL) {
                    CharacterStyle style = new RelativeSizeSpan(0.7f);
                    formatted.setSpan(style, magic1, magic2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
                }
                formatted.delete(magic2, magic2 + 1);
                formatted.delete(magic1, magic1 + 1);
            }
            return formatted;
        }
    }
    return result;
}
Example 4
Project: open-bixi-gpstracker-master  File: SegmentOverlay.java View source code
private boolean commonOnTap(GeoPoint tappedGeoPoint) {
    List<Uri> tappedUri = new Vector<Uri>();
    Point tappedPoint = new Point();
    mProjection.toPixels(tappedGeoPoint, tappedPoint);
    for (MediaVO media : mMediaPath) {
        if (media.x < tappedPoint.x && tappedPoint.x < media.x + media.w && media.y < tappedPoint.y && tappedPoint.y < media.y + media.h) {
            //Log.d( TAG, String.format( "Tapped at a (x,y) (%d,%d)", tappedPoint.x, tappedPoint.y ) );
            tappedUri.add(media.uri);
        }
    }
    if (tappedUri.size() > 0) {
        return handleMediaTapList(tappedUri);
    } else {
        if (mTrackColoringMethod == DRAW_DOTS) {
            DotVO tapped = null;
            synchronized (// Switch the fresh path with the old Path object
            mDotPath) {
                int w = 25;
                for (DotVO dot : mDotPath) {
                    //                  Log.d( TAG, "Compare ("+dot.x+","+dot.y+") with tap ("+tappedPoint.x+","+tappedPoint.y+")" );
                    if (dot.x - w < tappedPoint.x && tappedPoint.x < dot.x + w && dot.y - w < tappedPoint.y && tappedPoint.y < dot.y + w) {
                        if (tapped == null) {
                            tapped = dot;
                        } else {
                            tapped = dot.distanceTo(tappedPoint) < tapped.distanceTo(tappedPoint) ? dot : tapped;
                        }
                    }
                }
            }
            if (tapped != null) {
                DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(mLoggerMap.getApplicationContext());
                String timetxt = timeFormat.format(new Date(tapped.time));
                UnitsI18n units = new UnitsI18n(mLoggerMap, null);
                double speed = units.conversionFromMetersPerSecond(tapped.speed);
                String speedtxt = String.format("%.1f %s", speed, units.getSpeedUnit());
                String text = mLoggerMap.getString(R.string.time_and_speed, timetxt, speedtxt);
                Toast toast = Toast.makeText(mLoggerMap, text, Toast.LENGTH_SHORT);
                toast.show();
            }
        }
        return false;
    }
}
Example 5
Project: AppCompat-Extension-Library-master  File: DateFormatUtils.java View source code
public static String getBestDateTimePattern(Locale locale, String skeleton) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        return DateFormat.getBestDateTimePattern(locale, skeleton);
    } else {
        // Try to improve the skeleton on older devices
        if (skeleton.equals("EMMMd"))
            return "E, MMM d";
        if (skeleton.equals("MMMMy"))
            return "MMMM yyyy";
        if (skeleton.equals("Hm"))
            return "H:m";
        if (skeleton.equals("hm"))
            return "h:m";
        return skeleton;
    }
}
Example 6
Project: enviroCar-app-master  File: DateUtils.java View source code
public static String getDateString(Context context, long date) {
    Calendar now = Calendar.getInstance();
    now.setTimeZone(TimeZone.getDefault());
    Calendar time = Calendar.getInstance();
    time.setTimeZone(TimeZone.getDefault());
    time.setTimeInMillis(date);
    if (now.get(Calendar.DATE) == time.get(Calendar.DATE)) {
        return context.getString(R.string.today);
    } else if (now.get(Calendar.DATE) - time.get(Calendar.DATE) == 1) {
        return context.getString(R.string.yesterday);
    } else {
        return DateFormat.format("EE, MM yyyy", time).toString();
    //            return DateFormat.format("MMMM dd yyyy, h:mm aa", time).toString();
    }
}
Example 7
Project: arduino-android-master  File: InputController.java View source code
public void handleGeigerMessage(char flag, int reading) {
    Log.d("SRM", "setTemp " + reading);
    if (flag == 'E') {
        mRadiationImage.setVisibility(ImageView.VISIBLE);
        mp.start();
    } else if (flag == 'R') {
        mRadiationImage.setVisibility(ImageView.INVISIBLE);
        mTemperature.setText("" + reading);
    } else if (flag == 'L') {
        String logText = mLogView.getText().toString();
        String timeFormatted = (String) DateFormat.format("hh:mm", new Date());
        mLogView.setText(logText + "\n" + timeFormatted + "\t\t\t" + reading);
    }
}
Example 8
Project: ijoomer-adv-sdk-master  File: IjoomerUtilities.java View source code
/**
	 * This method used to get date dialog.
	 * 
	 * @param strDate
	 *            represented date
	 * @param restrict
	 *            represented isRestrict
	 * @param target
	 *            represented [email protected] CustomClickListner}
	 */
public static void getDateDialog(final String strDate, boolean restrict, final CustomClickListner target) {
    Calendar date = getDateFromString(strDate);
    Calendar today = Calendar.getInstance();
    if (restrict && date.get(Calendar.YEAR) == today.get(Calendar.YEAR) && date.get(Calendar.MONTH) == today.get(Calendar.MONTH) && date.get(Calendar.DAY_OF_MONTH) == today.get(Calendar.DAY_OF_MONTH)) {
        date.add(Calendar.YEAR, -18);
    }
    IjoomerDataPickerView dateDlg = new IjoomerDataPickerView(mSmartAndroidActivity, new DatePickerDialog.OnDateSetListener() {

        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            Time chosenDate = new Time();
            chosenDate.set(dayOfMonth, monthOfYear, year);
            long dt = chosenDate.toMillis(true);
            CharSequence strDate = DateFormat.format(IjoomerApplicationConfiguration.dateFormat, dt);
            target.onClick(strDate.toString());
        }
    }, date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DATE), restrict);
    dateDlg.show();
}
Example 9
Project: jdroid-master  File: TimePickerDialogFragment.java View source code
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getActivity());
    View view = inflate(R.layout.jdroid_time_picker_dialog_fragment);
    dialogBuilder.setView(view);
    final TimePicker timePicker = (TimePicker) view.findViewById(R.id.timePicker);
    timePicker.setIs24HourView(DateFormat.is24HourFormat(getActivity()));
    timePicker.setCurrentHour(DateUtils.getHour(defaultTime, true));
    timePicker.setCurrentMinute(DateUtils.getMinute(defaultTime));
    dialogBuilder.setPositiveButton(getString(R.string.jdroid_ok), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int whichButton) {
            Date time = DateUtils.getTime(timePicker.getCurrentHour(), timePicker.getCurrentMinute());
            int requestCode = getTargetRequestCode();
            ((OnTimeSetListener) getTargetFragment()).onTimeSet(time, requestCode);
        }
    });
    dialogBuilder.setNegativeButton(getString(R.string.jdroid_cancel), null);
    return dialogBuilder.create();
}
Example 10
Project: apteryx-master  File: TextFormat.java View source code
public static String formatDateSmart(Context context, long time) {
    Calendar current = Calendar.getInstance();
    Calendar date = Calendar.getInstance();
    date.setTimeInMillis(time);
    int dayToday = current.get(Calendar.DAY_OF_YEAR);
    int day = date.get(Calendar.DAY_OF_YEAR);
    if (day == dayToday)
        return DateFormat.format("kk:mm", time).toString();
    StringBuilder result = new StringBuilder();
    if (dayToday - day == 1)
        result.append(context.getString(R.string.yesterday));
    else if (dayToday - day == -1)
        result.append(context.getString(R.string.tomorrow));
    else {
        if (current.get(Calendar.YEAR) == date.get(Calendar.YEAR))
            result.append("dd MMM");
        else
            result.append("dd MMM yyyy");
    }
    result.append(" kk:mm");
    return DateFormat.format(result.toString(), time).toString();
}
Example 11
Project: btpka3.github.com-master  File: MyTimeIntentService.java View source code
private void handleActionTime(int time) {
    Log.d(TAG, "-------------- handleActionTime : " + time);
    timeRunning = true;
    for (int i = 0; i < time; i++) {
        try {
            Thread.sleep(1000);
            Intent intent = new Intent(MainActivity.TIME_NOTIFY);
            CharSequence timeStr = DateFormat.format("hh:mm:ss", System.currentTimeMillis());
            intent.putExtra(EXTRA_TIME_DATA, timeStr);
            sendBroadcast(intent);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return;
        }
    }
    timeRunning = false;
}
Example 12
Project: xDrip-master  File: BgGraphBuilder.java View source code
public Axis xAxis() {
    Axis xAxis = new Axis();
    xAxis.setAutoGenerated(false);
    List<AxisValue> xAxisValues = new ArrayList<AxisValue>();
    GregorianCalendar now = new GregorianCalendar();
    GregorianCalendar today = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
    final java.text.DateFormat timeFormat = hourFormat();
    timeFormat.setTimeZone(TimeZone.getDefault());
    double start_hour_block = today.getTime().getTime();
    double timeNow = new Date().getTime();
    for (int l = 0; l <= 24; l++) {
        if ((start_hour_block + (60000 * 60 * (l))) < timeNow) {
            if ((start_hour_block + (60000 * 60 * (l + 1))) >= timeNow) {
                endHour = start_hour_block + (60000 * 60 * (l));
                l = 25;
            }
        }
    }
    for (int l = 0; l <= 24; l++) {
        double timestamp = (endHour - (60000 * 60 * l));
        xAxisValues.add(new AxisValue((long) (timestamp / fuzzer), (timeFormat.format(timestamp)).toCharArray()));
    }
    xAxis.setValues(xAxisValues);
    xAxis.setHasLines(true);
    xAxis.setTextSize(axisTextSize);
    return xAxis;
}
Example 13
Project: Subsonic-master  File: ChatAdapter.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ChatMessage message = this.getItem(position);
    ViewHolder holder;
    int layout;
    String messageUser = message.getUsername();
    Date messageTime = new java.util.Date(message.getTime());
    String messageText = message.getMessage();
    String me = UserUtil.getCurrentUsername(activity);
    if (messageUser.equals(me)) {
        layout = R.layout.chat_item_reverse;
    } else {
        layout = R.layout.chat_item;
    }
    if (convertView == null) {
        holder = new ViewHolder();
        convertView = LayoutInflater.from(activity).inflate(layout, parent, false);
        TextView usernameView = (TextView) convertView.findViewById(R.id.chat_username);
        TextView timeView = (TextView) convertView.findViewById(R.id.chat_time);
        TextView messageView = (TextView) convertView.findViewById(R.id.chat_message);
        messageView.setMovementMethod(LinkMovementMethod.getInstance());
        Linkify.addLinks(messageView, Linkify.EMAIL_ADDRESSES);
        Linkify.addLinks(messageView, Linkify.WEB_URLS);
        Linkify.addLinks(messageView, phoneMatcher, "tel:");
        holder.message = messageView;
        holder.username = usernameView;
        holder.time = timeView;
        holder.avatar = (ImageView) convertView.findViewById(R.id.chat_avatar);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity);
    String messageTimeFormatted = String.format("[%s]", timeFormat.format(messageTime));
    holder.username.setText(messageUser);
    holder.message.setText(messageText);
    holder.time.setText(messageTimeFormatted);
    imageLoader.loadAvatar(activity, holder.avatar, messageUser);
    return convertView;
}
Example 14
Project: astrid-master  File: CalendarView.java View source code
/**
     * @see android.view.View#onDraw(android.graphics.Canvas)
     */
@Override
protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    // Background
    canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), backgroundColorPaint);
    // Outermost border -- Start
    //        RectF outerMostBorder = new RectF();
    //
    //        outerMostBorder.set(5, 5, getMeasuredWidth() - 5, getMeasuredHeight() - 5);
    //        canvas.drawRoundRect(outerMostBorder, OUTER_BORDER_RADIUS, OUTER_BORDER_RADIUS, borderPaint);
    //
    //        outerMostBorder.set(6, 6, getMeasuredWidth() - 6, getMeasuredHeight() - 6);
    //        canvas.drawRoundRect(outerMostBorder, CURVE_RADIUS, CURVE_RADIUS, backColorPaint);
    // Outermost border -- end
    // Month border -- Start
    RectF rectF = new RectF();
    float monthTitleHeight = (MONTH_TEXT_SIZE + 10) * density;
    rectF.set(15, 15, getMeasuredWidth() - 15, monthTitleHeight);
    canvas.drawRoundRect(rectF, CURVE_RADIUS, CURVE_RADIUS, backgroundColorPaint);
    rectF.set(16, 16, getMeasuredWidth() - 16, monthTitleHeight - 1);
    // canvas.drawRoundRect(rectF, CURVE_RADIUS, CURVE_RADIUS, backColorPaint);
    // Month border -- end
    // Month left arrow -- Start
    Bitmap leftArrow = ((BitmapDrawable) getResources().getDrawable(R.drawable.icn_arrow_left)).getBitmap();
    leftArrowHeight = (int) (leftArrow.getHeight() * density / 2);
    leftArrowWidth = (int) (leftArrow.getWidth() * density / 2);
    leftArrowX = 5;
    leftArrowY = 4 + (int) ((monthTitleHeight / 2 - leftArrowHeight / 2));
    canvas.drawBitmap(leftArrow, new Rect(0, 0, leftArrow.getWidth(), leftArrow.getHeight()), new Rect(leftArrowX, leftArrowY, leftArrowX + leftArrowWidth, leftArrowY + leftArrowHeight), null);
    // Month left arrow -- End
    // Month right arrow -- Start
    Bitmap rightArrow = ((BitmapDrawable) getResources().getDrawable(R.drawable.icn_arrow_right)).getBitmap();
    rightArrowHeight = (int) (rightArrow.getHeight() * density / 2);
    rightArrowWidth = (int) (rightArrow.getWidth() * density / 2);
    rightArrowX = (int) (getMeasuredWidth() - (2 * density) - (PADDING * 3) - rightArrow.getWidth());
    rightArrowY = 4 + (int) ((monthTitleHeight / 2 - rightArrowHeight / 2));
    canvas.drawBitmap(rightArrow, new Rect(0, 0, rightArrow.getWidth(), rightArrow.getHeight()), new Rect(rightArrowX, rightArrowY, rightArrowX + rightArrowWidth, rightArrowY + rightArrowHeight), null);
    // Month right arrow -- End
    Calendar calendar = Calendar.getInstance();
    // Month text -- Start
    int monthX = getMeasuredWidth() / 2;
    int monthY = (int) (monthTitleHeight / 2 + 15);
    //$NON-NLS-1$
    String monthYear = (String) DateFormat.format("MMMM yyyy", getCoercedDate(calendar.getTime(), calendarDate));
    canvas.drawText(monthYear, monthX, monthY, monthCenterAlignLargePaint);
    // Month text -- End
    // Day heading -- Start
    int dayLeft = 3;
    int dayTop = (int) (monthTitleHeight + PADDING * 2);
    boxWidth = (getMeasuredWidth() - (PADDING * 2)) / 7.0f;
    boxHeight = (int) (((getMeasuredHeight() - (monthTitleHeight) - 16) - (PADDING * 8)) / 7);
    float textX = 0;
    float textY = 0;
    int firstDayOfWeek = calendar.getFirstDayOfWeek();
    calendar.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
    for (int i = 0; i < 7; i++) {
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        String day = DateUtils.getDayOfWeekString(dayOfWeek, DateUtils.LENGTH_SHORT);
        calendar.add(Calendar.DATE, 1);
        textX = dayLeft + boxWidth - TEXT_PADDING * 3;
        textY = dayTop + (boxHeight - boxHeight / 8) - TEXT_PADDING * 2;
        canvas.drawText(day, textX, textY, rightAlignPaint);
        dayLeft += boxWidth;
    }
    // Day heading -- End
    // Calendar -- Start
    // Reset the calendar to either today or the specified date
    calendar.setTime(getCoercedDate(new Date(), calendarDate));
    if (currentHighlightDay == -1) {
        currentHighlightDay = calendarDate.getTime() == 0 ? 0 : calendar.get(Calendar.DATE);
    }
    int today = -1;
    Calendar todayCalendar = Calendar.getInstance();
    if (calendar.get(Calendar.MONTH) == todayCalendar.get(Calendar.MONTH) && calendar.get(Calendar.YEAR) == todayCalendar.get(Calendar.YEAR))
        today = todayCalendar.get(Calendar.DATE);
    int lastDateOfThisMonth = calendar.getActualMaximum(Calendar.DATE);
    calendar.set(Calendar.DATE, 1);
    // offset for day of week
    int firstDayOfMonth = calendar.get(Calendar.DAY_OF_WEEK) - firstDayOfWeek + Calendar.SUNDAY;
    if (firstDayOfMonth == 0)
        firstDayOfMonth = 7;
    boolean firstTime = true;
    int dayOfMonth = 1;
    Paint colorPaint;
    Paint textPaint;
    dayLeftArr = new int[lastDateOfThisMonth];
    dayTopArr = new int[lastDateOfThisMonth];
    for (int i = 1; i <= 6; i++) {
        dayLeft = 1;
        dayTop += boxHeight + PADDING;
        for (int j = 1; j <= 7; j++) {
            if (firstTime && j != firstDayOfMonth) {
                dayLeft += boxWidth + PADDING;
                continue;
            }
            firstTime = false;
            if (dayOfMonth <= lastDateOfThisMonth) {
                if (currentHighlightDay == dayOfMonth) {
                    colorPaint = selectedCalendarPaint;
                    textPaint = calendarSelectedNumberRightAlignPaint;
                } else if (today == dayOfMonth) {
                    colorPaint = todayCalendarPaint;
                    textPaint = calendarSelectedNumberRightAlignPaint;
                } else {
                    colorPaint = backgroundColorPaint;
                    textPaint = calendarNumberRightAlignPaint;
                }
                dayLeftArr[dayOfMonth - 1] = dayLeft;
                dayTopArr[dayOfMonth - 1] = dayTop;
                rectF.set(dayLeft, dayTop, dayLeft + boxWidth, dayTop + boxHeight);
                //					if (j != 1)
                //					    canvas.drawLine(rectF.left, rectF.top, rectF.left, rectF.bottom, borderPaint);
                rectF.set(dayLeft + 1, dayTop, dayLeft + boxWidth - 1, dayTop + boxHeight);
                canvas.drawRoundRect(rectF, CURVE_RADIUS, CURVE_RADIUS, colorPaint);
                textX = dayLeft + boxWidth - TEXT_PADDING * 3;
                textY = dayTop + calendarNumberRightAlignPaint.getTextSize() + TEXT_PADDING;
                canvas.drawText(String.valueOf(dayOfMonth), textX, textY, textPaint);
                dayLeft += boxWidth + PADDING;
                dayOfMonth++;
            }
        }
    }
// Calendar -- End
}
Example 15
Project: platform_packages_apps_settings-master  File: ZenModeVoiceActivity.java View source code
/**
     * Produce a summary of the Zen mode change to be read aloud as TTS.
     */
private CharSequence getChangeSummary(int mode, int minutes) {
    int indefinite = -1;
    int byMinute = -1;
    int byHour = -1;
    int byTime = -1;
    switch(mode) {
        case Global.ZEN_MODE_ALARMS:
            indefinite = R.string.zen_mode_summary_alarms_only_indefinite;
            byMinute = R.plurals.zen_mode_summary_alarms_only_by_minute;
            byHour = R.plurals.zen_mode_summary_alarms_only_by_hour;
            byTime = R.string.zen_mode_summary_alarms_only_by_time;
            break;
        case Global.ZEN_MODE_OFF:
            indefinite = R.string.zen_mode_summary_always;
            break;
    }
    ;
    if (minutes < 0 || mode == Global.ZEN_MODE_OFF) {
        return getString(indefinite);
    }
    long time = System.currentTimeMillis() + minutes * MINUTES_MS;
    String skeleton = DateFormat.is24HourFormat(this, UserHandle.myUserId()) ? "Hm" : "hma";
    String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
    CharSequence formattedTime = DateFormat.format(pattern, time);
    Resources res = getResources();
    if (minutes < 60) {
        return res.getQuantityString(byMinute, minutes, minutes, formattedTime);
    } else if (minutes % 60 != 0) {
        return res.getString(byTime, formattedTime);
    } else {
        int hours = minutes / 60;
        return res.getQuantityString(byHour, hours, hours, formattedTime);
    }
}
Example 16
Project: plusTimer-master  File: Utils.java View source code
/**
     * Returns a String containing the date and time according the device's
     * settings and locale from
     * the timestamp
     *
     * @param context   the context
     * @param timestamp the timestamp to convert into a date & time
     *                  String
     * @return the String converted from the timestamp
     * @see android.text.format.DateFormat
     * @see java.text.DateFormat
     */
public static String dateTimeSecondsStringFromTimestamp(Context context, long timestamp) {
    String timeDate;
    String androidDateTime = dateTimeStringFromTimestamp(context, timestamp);
    String javaDateTime = DateFormat.getDateTimeInstance().format(new Date(timestamp));
    String AmPm = "";
    if (!Character.isDigit(androidDateTime.charAt(androidDateTime.length() - 1))) {
        if (androidDateTime.contains(new SimpleDateFormat().getDateFormatSymbols().getAmPmStrings()[Calendar.AM])) {
            AmPm = " " + new SimpleDateFormat().getDateFormatSymbols().getAmPmStrings()[Calendar.AM];
        } else {
            AmPm = " " + new SimpleDateFormat().getDateFormatSymbols().getAmPmStrings()[Calendar.PM];
        }
        androidDateTime = androidDateTime.replace(AmPm, "");
    }
    if (!Character.isDigit(javaDateTime.charAt(javaDateTime.length() - 1))) {
        javaDateTime = javaDateTime.replace(" " + new SimpleDateFormat().getDateFormatSymbols().getAmPmStrings()[Calendar.AM], "");
        javaDateTime = javaDateTime.replace(" " + new SimpleDateFormat().getDateFormatSymbols().getAmPmStrings()[Calendar.PM], "");
    }
    javaDateTime = javaDateTime.substring(javaDateTime.length() - 3);
    timeDate = androidDateTime.concat(javaDateTime);
    return timeDate.concat(AmPm);
}
Example 17
Project: WS171-development-master  File: RadioIssueReport.java View source code
// Largely stolen from LogViewer.java
private static String getRadioLog() throws IOException {
    Socket sock = new Socket("127.0.0.1", 5040);
    DataInputStream in = new DataInputStream(sock.getInputStream());
    StringBuilder log = new StringBuilder();
    // Set options
    sock.getOutputStream().write(RADIO_BUFFER_OPTIONS.getBytes());
    sock.getOutputStream().write('\n');
    sock.getOutputStream().write('\n');
    // Read in the log
    try {
        Calendar cal = new GregorianCalendar();
        while (true) {
            int length = in.readInt();
            long when = (long) in.readInt();
            byte[] bytes = new byte[length - 4];
            in.readFully(bytes);
            int tagEnd = next0(bytes, HEADER_SIZE - 4);
            int fileEnd = next0(bytes, tagEnd + 1);
            int messageEnd = next0(bytes, fileEnd + 1);
            CharSequence tag = forAsciiBytes(bytes, HEADER_SIZE - 4, tagEnd);
            CharSequence message = forAsciiBytes(bytes, fileEnd + 1, messageEnd);
            cal.setTimeInMillis(when * 1000);
            log.append(DateFormat.format("MM-dd kk:mm:ss ", cal));
            log.append(tag).append(": ").append(message).append("\n");
        }
    } catch (EOFException e) {
        Log.d(TAG, "reached end of stream");
    }
    return log.toString();
}
Example 18
Project: android_packages_apps-master  File: DayView.java View source code
public void handleOnResume() {
    initAccessibilityVariables();
    if (Utils.getSharedPreference(mContext, OtherPreferences.KEY_OTHER_1, false)) {
        mFutureBgColor = 0;
    } else {
        mFutureBgColor = mFutureBgColorRes;
    }
    mIs24HourFormat = DateFormat.is24HourFormat(mContext);
    mHourStrs = mIs24HourFormat ? CalendarData.s24Hours : CalendarData.s12HoursNoAmPm;
    mFirstDayOfWeek = Utils.getFirstDayOfWeek(mContext);
    mLastSelectionDay = 0;
    mLastSelectionHour = 0;
    mLastSelectedEvent = null;
    mSelectionMode = SELECTION_HIDDEN;
}
Example 19
Project: property-db-master  File: TextClock.java View source code
/**
     * Selects either one of [email protected] #getFormat12Hour()} or [email protected] #getFormat24Hour()}
     * depending on whether the user has selected 24-hour format.
     * 
     * @param handleTicker true if calling this method should schedule/unschedule the
     *                     time ticker, false otherwise
     */
private void chooseFormat(boolean handleTicker) {
    final boolean format24Requested = is24HourModeEnabled();
    if (format24Requested) {
        mFormat = abc(mFormat24, mFormat12, DEFAULT_FORMAT_24_HOUR);
    } else {
        mFormat = abc(mFormat12, mFormat24, DEFAULT_FORMAT_12_HOUR);
    }
    boolean hadSeconds = mHasSeconds;
    mHasSeconds = DateFormat.hasSeconds(mFormat);
    if (handleTicker && mAttached && hadSeconds != mHasSeconds) {
        if (hadSeconds)
            getHandler().removeCallbacks(mTicker);
        else
            mTicker.run();
    }
}
Example 20
Project: Appsii-master  File: ItemAgendaViewHolder.java View source code
@Override
public boolean bind(Object object) {
    Context context = itemView.getContext();
    if (object instanceof AgendaEvent) {
        AgendaEvent item = (AgendaEvent) object;
        mAgendaEvent = item;
        mTime.set(item.startMillis);
        mPrimaryText.setText(item.title);
        mSecondaryText.setText(item.calendarName);
        EventTimeDrawable drawable = (EventTimeDrawable) mImageView.getDrawable();
        boolean is24 = android.text.format.DateFormat.is24HourFormat(context);
        if (item.allDay) {
            drawable.setTime(true, /* allDay */
            mTime.monthDay, mTime.month, mTime.hour, mTime.minute, EventTimeDrawable.AMPM_NONE);
        } else if (is24 && false) {
            drawable.setTime(false, /* allDay */
            mTime.monthDay, mTime.month, mTime.hour, mTime.minute, EventTimeDrawable.AMPM_NONE);
        } else {
            if (mTime.hour > 12) {
                drawable.setTime(false, /* allDay */
                mTime.monthDay, mTime.month, mTime.hour - 12, mTime.minute, EventTimeDrawable.AMPM_PM);
            } else {
                drawable.setTime(false, /* allDay */
                mTime.monthDay, mTime.month, mTime.hour, mTime.minute, EventTimeDrawable.AMPM_AM);
            }
        }
        return true;
    } else {
        mAgendaEvent = null;
        return false;
    }
}
Example 21
Project: WordPress-Android-master  File: EditPostSettingsFragment.java View source code
private void showPostTimeSelectionDialog() {
    final TimePicker timePicker = new TimePicker(getActivity());
    timePicker.setIs24HourView(DateFormat.is24HourFormat(getActivity()));
    timePicker.setCurrentHour(mHour);
    timePicker.setCurrentMinute(mMinute);
    new AlertDialog.Builder(getActivity()).setTitle(R.string.select_time).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            mHour = timePicker.getCurrentHour();
            mMinute = timePicker.getCurrentMinute();
            Date d = new Date(mYear - 1900, mMonth, mDay, mHour, mMinute);
            long timestamp = d.getTime();
            try {
                int flags = 0;
                flags |= DateUtils.FORMAT_SHOW_DATE;
                flags |= DateUtils.FORMAT_ABBREV_MONTH;
                flags |= DateUtils.FORMAT_SHOW_YEAR;
                flags |= DateUtils.FORMAT_SHOW_TIME;
                String formattedDate = DateUtils.formatDateTime(getActivity(), timestamp, flags);
                mCustomPubDate = timestamp;
                mPubDateText.setText(formattedDate);
                mIsCustomPubDate = true;
                updatePostSettingsAndSaveButton();
            } catch (RuntimeException e) {
                AppLog.e(T.POSTS, e);
            }
        }
    }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
        }
    }).setView(timePicker).show();
}
Example 22
Project: CSipSimple-old-master  File: PreferencesWrapper.java View source code
public static File getLogsFile(Context ctxt, boolean isPjsip) {
    File dir = PreferencesWrapper.getLogsFolder(ctxt);
    File outFile = null;
    if (dir != null) {
        Date d = new Date();
        StringBuffer fileName = new StringBuffer();
        if (isPjsip) {
            fileName.append("pjsip");
        }
        fileName.append("logs_");
        fileName.append(DateFormat.format("yy-MM-dd_kkmmss", d));
        fileName.append(".txt");
        outFile = new File(dir.getAbsoluteFile() + File.separator + fileName.toString());
    }
    return outFile;
}
Example 23
Project: FORMWatchFace-master  File: FormWatchFace.java View source code
private void initClockRenderers() {
    // Init paints
    mAmbientBackgroundPaint = new Paint();
    mAmbientBackgroundPaint.setColor(Color.BLACK);
    mBackgroundPaint = new Paint();
    Paint paint = new Paint();
    paint.setAntiAlias(true);
    mNormalPaints = new ClockPaints();
    mNormalPaints.fills[0] = paint;
    mNormalPaints.fills[1] = new Paint(paint);
    mNormalPaints.fills[2] = new Paint(paint);
    mNormalPaints.date = new Paint(paint);
    mNormalPaints.date.setTypeface(mDateTypeface);
    mNormalPaints.date.setTextSize(getResources().getDimensionPixelSize(R.dimen.seconds_clock_height));
    rebuildAmbientPaints();
    // General config
    FormClockRenderer.Options options = new FormClockRenderer.Options();
    options.is24hour = DateFormat.is24HourFormat(FormWatchFace.this);
    options.textSize = getResources().getDimensionPixelSize(R.dimen.main_clock_height);
    options.charSpacing = getResources().getDimensionPixelSize(R.dimen.main_clock_spacing);
    options.glyphAnimAverageDelay = getResources().getInteger(R.integer.main_clock_glyph_anim_delay);
    options.glyphAnimDuration = getResources().getInteger(R.integer.main_clock_glyph_anim_duration);
    mHourMinRenderer = new FormClockRenderer(options, mNormalPaints);
    options = new FormClockRenderer.Options(options);
    options.textSize = getResources().getDimensionPixelSize(R.dimen.seconds_clock_height);
    options.onlySeconds = true;
    options.charSpacing = getResources().getDimensionPixelSize(R.dimen.seconds_clock_spacing);
    options.glyphAnimAverageDelay = getResources().getInteger(R.integer.seconds_clock_glyph_anim_delay);
    options.glyphAnimDuration = getResources().getInteger(R.integer.seconds_clock_glyph_anim_duration);
    mSecondsRenderer = new FormClockRenderer(options, mNormalPaints);
}
Example 24
Project: mobile-mba-androidapp-master  File: SKDateFormat.java View source code
private String dateFormat() {
    char[] order = DateFormat.getDateFormatOrder(mCtx);
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < order.length; i++) {
        if (i != 0) {
            sb.append("/");
        }
        switch(order[i]) {
            case DateFormat.DATE:
                sb.append("dd");
                break;
            case DateFormat.MONTH:
                sb.append("MM");
                break;
            case DateFormat.YEAR:
                sb.append("yyyy");
                break;
        }
    }
    return sb.toString();
}
Example 25
Project: aLogMyNight-master  File: CameraActivity.java View source code
public void onPictureTaken(final byte[] data, Camera camera) {
    Log.d(TAG, "onPictureTaken() started ");
    /* First, get the Display from the WindowManager */
    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    /* Now we can retrieve all display-related infos */
    final int orientation = display.getOrientation();
    Log.d(TAG, "Orientation: " + orientation);
    final Dialog dlg = new Dialog(this);
    View view = getLayoutInflater().inflate(R.layout.cameradialog, null);
    Button okButton = (Button) view.findViewById(R.id.cameraDialogOKButton);
    final EditText edit = (EditText) view.findViewById(R.id.cameraDialogEditText);
    okButton.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            dlg.dismiss();
            String name = edit.getText().toString();
            Log.d(TAG, "Entered name: " + name);
            String filename = DateFormat.format("yyyyMMdd-kkmmss", new Date()) + ".jpg";
            new SavePhotoAsyncTask(filename).execute(data);
            db.execSQL("INSERT INTO pics (name, filename, orientation) VALUES (?,?,?)", new String[] { name, filename, String.valueOf(orientation) });
            finish();
        }
    });
    dlg.setContentView(view);
    dlg.setTitle("Enter name:");
    dlg.show();
    Log.d(TAG, "onPictureTaken() finished");
}
Example 26
Project: android-sdk-sources-for-api-level-23-master  File: ProcessStats.java View source code
void dumpTotalsLocked(PrintWriter pw, long now) {
    pw.println("Run time Stats:");
    dumpSingleTime(pw, "  ", mMemFactorDurations, mMemFactor, mStartTime, now);
    pw.println();
    pw.println("Memory usage:");
    TotalMemoryUseCollection totalMem = new TotalMemoryUseCollection(ALL_SCREEN_ADJ, ALL_MEM_ADJ);
    computeTotalMemoryUse(totalMem, now);
    long totalPss = 0;
    totalPss = printMemoryCategory(pw, "  ", "Kernel ", totalMem.sysMemKernelWeight, totalMem.totalTime, totalPss, totalMem.sysMemSamples);
    totalPss = printMemoryCategory(pw, "  ", "Native ", totalMem.sysMemNativeWeight, totalMem.totalTime, totalPss, totalMem.sysMemSamples);
    for (int i = 0; i < STATE_COUNT; i++) {
        // Skip restarting service state -- that is not actually a running process.
        if (i != STATE_SERVICE_RESTARTING) {
            totalPss = printMemoryCategory(pw, "  ", STATE_NAMES[i], totalMem.processStateWeight[i], totalMem.totalTime, totalPss, totalMem.processStateSamples[i]);
        }
    }
    totalPss = printMemoryCategory(pw, "  ", "Cached ", totalMem.sysMemCachedWeight, totalMem.totalTime, totalPss, totalMem.sysMemSamples);
    totalPss = printMemoryCategory(pw, "  ", "Free   ", totalMem.sysMemFreeWeight, totalMem.totalTime, totalPss, totalMem.sysMemSamples);
    totalPss = printMemoryCategory(pw, "  ", "Z-Ram  ", totalMem.sysMemZRamWeight, totalMem.totalTime, totalPss, totalMem.sysMemSamples);
    pw.print("  TOTAL  : ");
    DebugUtils.printSizeValue(pw, totalPss);
    pw.println();
    printMemoryCategory(pw, "  ", STATE_NAMES[STATE_SERVICE_RESTARTING], totalMem.processStateWeight[STATE_SERVICE_RESTARTING], totalMem.totalTime, totalPss, totalMem.processStateSamples[STATE_SERVICE_RESTARTING]);
    pw.println();
    pw.print("          Start time: ");
    pw.print(DateFormat.format("yyyy-MM-dd HH:mm:ss", mTimePeriodStartClock));
    pw.println();
    pw.print("  Total elapsed time: ");
    TimeUtils.formatDuration((mRunning ? SystemClock.elapsedRealtime() : mTimePeriodEndRealtime) - mTimePeriodStartRealtime, pw);
    boolean partial = true;
    if ((mFlags & FLAG_SHUTDOWN) != 0) {
        pw.print(" (shutdown)");
        partial = false;
    }
    if ((mFlags & FLAG_SYSPROPS) != 0) {
        pw.print(" (sysprops)");
        partial = false;
    }
    if ((mFlags & FLAG_COMPLETE) != 0) {
        pw.print(" (complete)");
        partial = false;
    }
    if (partial) {
        pw.print(" (partial)");
    }
    pw.print(' ');
    pw.print(mRuntime);
    pw.println();
}
Example 27
Project: devcoin-android-master  File: TransactionsListFragment.java View source code
@Override
public boolean onPrepareActionMode(final ActionMode mode, final Menu menu) {
    try {
        final Date time = tx.getUpdateTime();
        final DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(activity);
        final DateFormat timeFormat = android.text.format.DateFormat.getTimeFormat(activity);
        mode.setTitle(time != null ? (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time)) + ", " + timeFormat.format(time) : null);
        final BigInteger value = tx.getValue(wallet);
        final boolean sent = value.signum() < 0;
        address = sent ? WalletUtils.getFirstToAddress(tx) : WalletUtils.getFirstFromAddress(tx);
        final String label;
        if (tx.isCoinBase())
            label = getString(R.string.wallet_transactions_fragment_coinbase);
        else if (address != null)
            label = AddressBookProvider.resolveLabel(activity, address.toString());
        else
            label = "?";
        final String prefix = getString(sent ? R.string.symbol_to : R.string.symbol_from) + " ";
        if (tx.getPurpose() != Purpose.KEY_ROTATION)
            mode.setSubtitle(label != null ? prefix + label : WalletUtils.formatAddress(prefix, address, Constants.ADDRESS_FORMAT_GROUP_SIZE, Constants.ADDRESS_FORMAT_LINE_SIZE));
        else
            mode.setSubtitle(null);
        menu.findItem(R.id.wallet_transactions_context_edit_address).setVisible(address != null);
        serializedTx = tx.unsafeBitcoinSerialize();
        menu.findItem(R.id.wallet_transactions_context_show_qr).setVisible(serializedTx.length < SHOW_QR_THRESHOLD_BYTES);
        Nfc.publishMimeObject(nfcManager, activity, Constants.MIMETYPE_TRANSACTION, serializedTx, false);
        return true;
    } catch (final ScriptException x) {
        return false;
    }
}
Example 28
Project: SulfurKeyboard-master  File: TextEntryState.java View source code
public static void endSession() {
    if (sKeyLocationFile == null) {
        return;
    }
    try {
        sKeyLocationFile.close();
        // Write to log file            
        // Write timestamp, settings,
        String out = DateFormat.format("MM:dd hh:mm:ss", Calendar.getInstance().getTime()).toString() + " BS: " + sBackspaceCount + " auto: " + sAutoSuggestCount + " manual: " + sManualSuggestCount + " typed: " + sWordNotInDictionaryCount + " undone: " + sAutoSuggestUndoneCount + " saved: " + ((float) (sActualChars - sTypedChars) / sActualChars) + "\n";
        sUserActionFile.write(out.getBytes());
        sUserActionFile.close();
        sKeyLocationFile = null;
        sUserActionFile = null;
    } catch (IOException ioe) {
    }
}
Example 29
Project: ngCordova-demo-master  File: Globalization.java View source code
/*
     * @Description: Parses a date formatted as a string according to the client's user
     * preferences and calendar using the time zone of the client and returns
     * the corresponding date object
     * @Return: JSONObject
     *          Object.year {Number}: The four digit year
     *          Object.month {Number}: The month from (0 - 11)
     *          Object.day {Number}: The day from (1 - 31)
     *          Object.hour {Number}: The hour from (0 - 23)
     *          Object.minute {Number}: The minute from (0 - 59)
     *          Object.second {Number}: The second from (0 - 59)
     *          Object.millisecond {Number}: The milliseconds (from 0 - 999), not available on all platforms
     *
     * @throws: GlobalizationError.PARSING_ERROR
    */
private JSONObject getStringtoDate(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();
    Date date;
    try {
        //get format pattern from android device (Will only have device specific formatting for short form of date) or options supplied
        DateFormat fmt = new SimpleDateFormat(getDatePattern(options).getString("pattern"));
        //attempt parsing string based on user preferences
        date = fmt.parse(options.getJSONObject(0).get(DATESTRING).toString());
        //set Android Time object
        Time time = new Time();
        time.set(date.getTime());
        //return properties;
        obj.put("year", time.year);
        obj.put("month", time.month);
        obj.put("day", time.monthDay);
        obj.put("hour", time.hour);
        obj.put("minute", time.minute);
        obj.put("second", time.second);
        obj.put("millisecond", Long.valueOf(0));
        return obj;
    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PARSING_ERROR);
    }
}
Example 30
Project: deck_old-master  File: GameSaveIO.java View source code
@Override
public void onBindViewHolder(final GameSaveHolder gameSaveHolder, final int position) {
    final File gameSave = getItem(position);
    gameSaveHolder.Title.setText(getGameSaveNameFromFile(gameSave));
    gameSaveHolder.Subtitle.setText(DateFormat.format("h:mm aa - MMMM d, yyyy", gameSave.lastModified()));
    gameSaveHolder.Card.setOnTouchListener(new SwipeDismissTouchListener(gameSaveHolder.Card, null, new SwipeDismissTouchListener.OnDismissCallback() {

        @Override
        public void onDismiss(View view, Object token) {
            GameSaveCardAdapter.this.removeItemAt(position);
        }
    }));
    gameSaveHolder.Card.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            if (mListener != null) {
                mListener.onGameSaveClick(gameSave);
            }
        }
    });
    final HashMap<String, CardHolder> cardHolders = new HashMap<String, CardHolder>();
    if (GameSaveIO.openGameSave(gameSave, cardHolders, cardHolders)) {
        final StringBuilder sb = new StringBuilder();
        for (CardHolder cardHolder : cardHolders.values()) {
            sb.append(cardHolder.getName()).append("\n");
            if (BuildConfig.DEBUG) {
                for (Card card : cardHolder.getCards()) {
                    sb.append("\t").append(card.toString()).append("\n");
                }
            }
        }
        sb.deleteCharAt(sb.length() - 1);
        gameSaveHolder.Players.setText(sb.toString());
    }
}
Example 31
Project: platform-friends-android-master  File: CreateNewUserActivity.java View source code
private void displayDatePicker() {
    final Calendar myCalendar = Calendar.getInstance();
    DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            myCalendar.set(Calendar.YEAR, year);
            myCalendar.set(Calendar.MONTH, monthOfYear);
            myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }

        private void updateLabel() {
            DateFormat dateFormat = getDateFormat();
            birthDay.setText(dateFormat.format(myCalendar.getTime()));
        }
    };
    new DatePickerDialog(CreateNewUserActivity.this, date, myCalendar.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH), myCalendar.get(Calendar.DAY_OF_MONTH)).show();
}
Example 32
Project: traffic-balance-master  File: MapInfoLayer.java View source code
private void drawRouteInfo(Canvas canvas) {
    if (routeLayer != null && routeLayer.getHelper().isRouterEnabled()) {
        if (routeLayer.getHelper().isFollowingMode()) {
            int d = routeLayer.getHelper().getDistanceToNextRouteDirection();
            if (showMiniMap || d == 0) {
                if (!routeLayer.getPath().isEmpty()) {
                    canvas.save();
                    canvas.clipRect(boundsForMiniRoute);
                    canvas.drawRoundRect(boundsForMiniRoute, roundCorner, roundCorner, paintAlphaGray);
                    canvas.drawRoundRect(boundsForMiniRoute, roundCorner, roundCorner, paintBlack);
                    canvas.translate(centerMiniRouteX - view.getCenterPointX(), centerMiniRouteY - view.getCenterPointY());
                    canvas.scale(scaleMiniRoute, scaleMiniRoute, view.getCenterPointX(), view.getCenterPointY());
                    canvas.rotate(view.getRotate(), view.getCenterPointX(), view.getCenterPointY());
                    canvas.drawCircle(view.getCenterPointX(), view.getCenterPointY(), 3 / scaleMiniRoute, fillBlack);
                    canvas.drawPath(routeLayer.getPath(), paintMiniRoute);
                    canvas.restore();
                }
            } else {
                canvas.drawRoundRect(boundsForMiniRoute, roundCorner, roundCorner, paintAlphaGray);
                canvas.drawRoundRect(boundsForMiniRoute, roundCorner, roundCorner, paintBlack);
                RouteDirectionInfo next = routeLayer.getHelper().getNextRouteDirectionInfo();
                if (next != null) {
                    if (!Algoritms.objectEquals(cachedTurnType, next.turnType)) {
                        cachedTurnType = next.turnType;
                        calcTurnPath(pathForTurn, cachedTurnType, pathTransform);
                        if (cachedTurnType.getExitOut() > 0) {
                            cachedExitOut = //$NON-NLS-1$
                            cachedTurnType.getExitOut() + "";
                        } else {
                            cachedExitOut = null;
                        }
                    }
                    canvas.drawPath(pathForTurn, paintRouteDirection);
                    canvas.drawPath(pathForTurn, paintBlack);
                    if (cachedExitOut != null) {
                        canvas.drawText(cachedExitOut, boundsForMiniRoute.centerX() - 6 * scaleCoefficient, boundsForMiniRoute.centerY() - 9 * scaleCoefficient, paintBlack);
                    }
                    canvas.drawText(OsmAndFormatter.getFormattedDistance(d, map), boundsForMiniRoute.left + 10 * scaleCoefficient, boundsForMiniRoute.bottom - 9 * scaleCoefficient, paintBlack);
                }
            }
        }
        boolean followingMode = routeLayer.getHelper().isFollowingMode();
        int time = routeLayer.getHelper().getLeftTime();
        if (time == 0) {
            cachedLeftTime = 0;
            cachedLeftTimeString = null;
        } else {
            if (followingMode && showArrivalTime) {
                long toFindTime = time * 1000 + System.currentTimeMillis();
                if (Math.abs(toFindTime - cachedLeftTime) > 30000) {
                    cachedLeftTime = toFindTime;
                    if (DateFormat.is24HourFormat(map)) {
                        cachedLeftTimeString = //$NON-NLS-1$
                        DateFormat.format(//$NON-NLS-1$
                        "kk:mm", //$NON-NLS-1$
                        toFindTime).toString();
                    } else {
                        cachedLeftTimeString = //$NON-NLS-1$
                        DateFormat.format(//$NON-NLS-1$
                        "k:mm aa", //$NON-NLS-1$
                        toFindTime).toString();
                    }
                    boundsForLeftTime.left = -paintBlack.measureText(cachedLeftTimeString) - 10 * scaleCoefficient + boundsForLeftTime.right;
                }
            } else {
                if (Math.abs(time - cachedLeftTime) > 30) {
                    cachedLeftTime = time;
                    int hours = time / (60 * 60);
                    int minutes = (time / 60) % 60;
                    cachedLeftTimeString = //$NON-NLS-1$
                    String.format(//$NON-NLS-1$
                    "%d:%02d", //$NON-NLS-1$
                    hours, //$NON-NLS-1$
                    minutes);
                    boundsForLeftTime.left = -paintBlack.measureText(cachedLeftTimeString) - 10 * scaleCoefficient + boundsForLeftTime.right;
                }
            }
        }
        if (cachedLeftTimeString != null) {
            int w = (int) (boundsForLeftTime.right - boundsForLeftTime.left);
            boundsForLeftTime.right = view.getWidth();
            boundsForLeftTime.left = view.getWidth() - w;
            canvas.drawRoundRect(boundsForLeftTime, roundCorner, roundCorner, paintAlphaGray);
            canvas.drawRoundRect(boundsForLeftTime, roundCorner, roundCorner, paintBlack);
            canvas.drawText(cachedLeftTimeString, boundsForLeftTime.left + 5 * scaleCoefficient, boundsForLeftTime.bottom - 9 * scaleCoefficient, paintBlack);
        }
    }
}
Example 33
Project: my-ministry-assistant-master  File: DBScheduleFragment.java View source code
@Override
public void onClick(View v) {
    PrefUtils.setDBBackupDaily(getActivity(), cb_is_active_daily.isChecked());
    PrefUtils.setDBBackupDailyTime(getActivity(), DateFormat.getTimeFormat(getActivity().getApplicationContext()).format(daily.getTime()).toString());
    if (cb_is_active_daily.isChecked()) {
        HelpUtils.setDailyAlarm(getActivity().getApplicationContext());
        Toast.makeText(getActivity().getApplicationContext(), Phrase.from(getActivity().getApplicationContext(), R.string.toast_daily_backup_scheduled).put("time", DateFormat.getTimeFormat(getActivity().getApplicationContext()).format(daily.getTime())).format(), Toast.LENGTH_LONG).show();
        enableBootReceiver();
    } else {
        HelpUtils.disableDailyAlarm(getActivity().getApplicationContext());
        Toast.makeText(getActivity().getApplicationContext(), getActivity().getResources().getString(R.string.toast_daily_backup_cancelled), Toast.LENGTH_LONG).show();
        if (PrefUtils.shouldDBBackupWeekly(getActivity())) {
            disableBootReceiver();
        }
    }
}
Example 34
Project: WS171-frameworks-base-master  File: Notification.java View source code
/**
     * Sets the [email protected] #contentView} field to be a view with the standard "Latest Event"
     * layout.
     *
     * <p>Uses the [email protected] #icon} and [email protected] #when} fields to set the icon and time fields
     * in the view.</p>
     * @param context       The context for your application / activity.
     * @param contentTitle The title that goes in the expanded entry.
     * @param contentText  The text that goes in the expanded entry.
     * @param contentIntent The intent to launch when the user clicks the expanded notification.
     * If this is an activity, it must include the
     * [email protected] android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag, which requires
     * that you take care of task management as described in 
     * <a href="[email protected]}guide/topics/fundamentals.html#lcycles">Application Fundamentals: Activities and Tasks</a>.
     */
public void setLatestEventInfo(Context context, CharSequence contentTitle, CharSequence contentText, PendingIntent contentIntent) {
    RemoteViews contentView = new RemoteViews(context.getPackageName(), com.android.internal.R.layout.status_bar_latest_event_content);
    if (this.icon != 0) {
        contentView.setImageViewResource(com.android.internal.R.id.icon, this.icon);
    }
    if (contentTitle != null) {
        contentView.setTextViewText(com.android.internal.R.id.title, contentTitle);
    }
    if (contentText != null) {
        contentView.setTextViewText(com.android.internal.R.id.text, contentText);
    }
    if (this.when != 0) {
        Date date = new Date(when);
        CharSequence str = DateUtils.isToday(when) ? DateFormat.getTimeFormat(context).format(date) : DateFormat.getDateFormat(context).format(date);
        contentView.setTextViewText(com.android.internal.R.id.time, str);
    }
    this.contentView = contentView;
    this.contentIntent = contentIntent;
}
Example 35
Project: SealBrowser-master  File: InputDialogContainer.java View source code
void showPickerDialog(final int dialogType, int year, int month, int monthDay, int hourOfDay, int minute, int second, int millis, int week, double min, double max, double step) {
    if (isDialogShowing())
        mDialog.dismiss();
    int stepTime = (int) step;
    if (dialogType == sTextInputTypeDate) {
        DatePickerDialog dialog = new DatePickerDialog(mContext, new DateListener(dialogType), year, month, monthDay);
        DateDialogNormalizer.normalize(dialog.getDatePicker(), dialog, year, month, monthDay, 0, 0, (long) min, (long) max);
        dialog.setTitle(mContext.getText(R.string.date_picker_dialog_title));
        mDialog = dialog;
    } else if (dialogType == sTextInputTypeTime) {
        mDialog = new MultiFieldTimePickerDialog(mContext, 0, /* theme */
        hourOfDay, minute, second, millis, (int) min, (int) max, stepTime, DateFormat.is24HourFormat(mContext), new FullTimeListener(dialogType));
    } else if (dialogType == sTextInputTypeDateTime || dialogType == sTextInputTypeDateTimeLocal) {
        mDialog = new DateTimePickerDialog(mContext, new DateTimeListener(dialogType), year, month, monthDay, hourOfDay, minute, DateFormat.is24HourFormat(mContext), min, max);
    } else if (dialogType == sTextInputTypeMonth) {
        mDialog = new MonthPickerDialog(mContext, new MonthOrWeekListener(dialogType), year, month, min, max);
    } else if (dialogType == sTextInputTypeWeek) {
        mDialog = new WeekPickerDialog(mContext, new MonthOrWeekListener(dialogType), year, week, min, max);
    }
    mDialog.setButton(DialogInterface.BUTTON_POSITIVE, mContext.getText(R.string.date_picker_dialog_set), (DialogInterface.OnClickListener) mDialog);
    mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, mContext.getText(android.R.string.cancel), (DialogInterface.OnClickListener) null);
    mDialog.setButton(DialogInterface.BUTTON_NEUTRAL, mContext.getText(R.string.date_picker_dialog_clear), new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            mDialogAlreadyDismissed = true;
            mInputActionDelegate.replaceDateTime(Double.NaN);
        }
    });
    mDialog.setOnDismissListener(new OnDismissListener() {

        @Override
        public void onDismiss(final DialogInterface dialog) {
            if (!mDialogAlreadyDismissed) {
                mDialogAlreadyDismissed = true;
                mInputActionDelegate.cancelDateTimeDialog();
            }
        }
    });
    mDialogAlreadyDismissed = false;
    mDialog.show();
}
Example 36
Project: ohmagePhone-master  File: MobilityControlFragment.java View source code
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.mobility_control_layout, container, false);
    mMobilityList = (ListView) view.findViewById(R.id.mobility_list);
    mTotalCountText = (TextView) view.findViewById(R.id.mobility_total);
    mUploadCountText = (TextView) view.findViewById(R.id.mobility_count);
    mLastUploadText = (TextView) view.findViewById(R.id.last_upload);
    mUploadButton = (Button) view.findViewById(R.id.upload_button);
    mOffRadio = (RadioButton) view.findViewById(R.id.radio_off);
    mInterval1Radio = (RadioButton) view.findViewById(R.id.radio_1min);
    mInterval5Radio = (RadioButton) view.findViewById(R.id.radio_5min);
    TextView emptyView = (TextView) view.findViewById(R.id.empty);
    mMobilityList.setEmptyView(emptyView);
    String[] from = new String[] { MobilityInterface.KEY_MODE, MobilityInterface.KEY_TIME };
    int[] to = new int[] { R.id.text1, R.id.text2 };
    mAdapter = new SimpleCursorAdapter(getActivity(), R.layout.mobility_list_item, null, from, to, 0);
    mAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            switch(view.getId()) {
                case R.id.text1:
                    ((TextView) view).setText(cursor.getString(columnIndex));
                    return true;
                case R.id.text2:
                    long time = cursor.getLong(columnIndex);
                    ((TextView) view).setText(DateFormat.format("h:mmaa", time));
                    return true;
            }
            return false;
        }
    });
    mMobilityList.setAdapter(mAdapter);
    mTotalCountText.setText(emptyValue);
    mUploadCountText.setText(emptyValue);
    mOffRadio.setChecked(true);
    mUploadButton.setOnClickListener(mUploadListener);
    return view;
}
Example 37
Project: Notes-master  File: DateTimePicker.java View source code
private void updateDateControl() {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(mDate.getTimeInMillis());
    cal.add(Calendar.DAY_OF_YEAR, -DAYS_IN_ALL_WEEK / 2 - 1);
    mDateSpinner.setDisplayedValues(null);
    for (int i = 0; i < DAYS_IN_ALL_WEEK; ++i) {
        cal.add(Calendar.DAY_OF_YEAR, 1);
        mDateDisplayValues[i] = (String) DateFormat.format("MM.dd EEEE", cal);
    }
    mDateSpinner.setDisplayedValues(mDateDisplayValues);
    mDateSpinner.setValue(DAYS_IN_ALL_WEEK / 2);
    mDateSpinner.invalidate();
}
Example 38
Project: TestingStuff-master  File: SettingServiceImpl.java View source code
@Override
public void addUserLogWithSection(String aSection, String aSectionSubCat, String aType, String aContentId, String aContentName, String aEvent, String aDetail) throws FanclException {
    // TODO Auto-generated method stub
    Exception exception = null;
    SQLiteDatabase dB = null;
    try {
        dB = GeneralServiceFactory.getSQLiteDatabaseService().getUserLogDatabase();
        if (dB != null) {
            String section = "";
            if (aSection != null) {
                section = aSection;
            }
            String sectionSubCat = "";
            if (aSectionSubCat != null) {
                sectionSubCat = aSectionSubCat;
            }
            String type = "";
            if (aType != null) {
                type = aType;
            }
            String contentId = "";
            if (aContentId != null) {
                contentId = aContentId;
            }
            String contentName = "";
            if (aContentName != null) {
                contentName = aContentName;
            }
            String event = "";
            if (aEvent != null) {
                event = aEvent;
            }
            String detail = "";
            if (aDetail != null) {
                detail = aDetail;
            }
            LogController.log("dB != null");
            Date now = new Date();
            String nowFullStr = DateFormat.format("yyyy-MM-dd hh:mm:ss", now).toString();
            String tmpContentName = contentName.replace("'", " ");
            String insertValue = "('" + section + "', '" + sectionSubCat + "', '" + type + "', '" + contentId + "', '" + tmpContentName + "', '" + event + "', '" + detail + "', '" + nowFullStr + "', '" + CustomServiceFactory.getAccountService().currentMemberId() + "')";
            String sql = "";
            sql = "INSERT INTO userLog (section, section_sub_cat, type, content_id, content_name, event, detail, log_datetime, member_sk) VALUES " + insertValue + ";";
            dB.execSQL(sql);
            LogController.log("userlog added-" + "Section:" + aSection + ",SectionSubCat:" + aSectionSubCat + ",Type:" + aType + ",ContentId:" + aContentId + ",ContentName:" + aContentName + ",Event:" + aEvent + ",Detail:" + aDetail);
        }
    } catch (Exception e) {
        e.printStackTrace();
        exception = e;
        LogController.log("userlog cannot add");
    }
    if (exception != null) {
        throw new FanclException(Constants.STATUS_CODE_FAIL, exception.getMessage());
    }
}
Example 39
Project: android_packages_apps_Gallery3D-master  File: MediaClustering.java View source code
public void generateCaption(Context context) {
    if (mClusterChanged) {
        Resources resources = context.getResources();
        long minTimestamp = -1L;
        long maxTimestamp = -1L;
        if (areTimestampsAvailable()) {
            minTimestamp = mMinTimestamp;
            maxTimestamp = mMaxTimestamp;
        } else if (areAddedTimestampsAvailable()) {
            minTimestamp = mMinAddedTimestamp;
            maxTimestamp = mMaxAddedTimestamp;
        }
        if (minTimestamp != -1L) {
            if (mIsPicassaAlbum) {
                minTimestamp -= App.CURRENT_TIME_ZONE.getOffset(minTimestamp);
                maxTimestamp -= App.CURRENT_TIME_ZONE.getOffset(maxTimestamp);
            }
            String minDay = DateFormat.format(MMDDYY_FORMAT, minTimestamp).toString();
            String maxDay = DateFormat.format(MMDDYY_FORMAT, maxTimestamp).toString();
            if (minDay.substring(4).equals(maxDay.substring(4))) {
                // The items are from the same year - show at least as
                // much granularity as abbrev_all allows.
                mName = DateUtils.formatDateRange(context, minTimestamp, maxTimestamp, DateUtils.FORMAT_ABBREV_ALL);
                // current year.
                if (minDay.equals(maxDay)) {
                    int flags = DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE;
                    // Contains the year only if the date does not
                    // correspond to the current year.
                    String dateRangeWithOptionalYear = DateUtils.formatDateTime(context, minTimestamp, flags);
                    String dateRangeWithYear = DateUtils.formatDateTime(context, minTimestamp, flags | DateUtils.FORMAT_SHOW_YEAR);
                    if (!dateRangeWithOptionalYear.equals(dateRangeWithYear)) {
                        // This means both dates are from the same year
                        // - show the time.
                        // Not enough room to display the time range.
                        // Pick the mid-point.
                        long midTimestamp = (minTimestamp + maxTimestamp) / 2;
                        mName = DateUtils.formatDateRange(context, midTimestamp, midTimestamp, DateUtils.FORMAT_SHOW_TIME | flags);
                    }
                }
            } else {
                // The items are not from the same year - only show
                // month and year.
                int flags = DateUtils.FORMAT_NO_MONTH_DAY | DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE;
                mName = DateUtils.formatDateRange(context, minTimestamp, maxTimestamp, flags);
            }
        } else {
            mName = resources.getString(Res.string.date_unknown);
        }
        updateNumExpectedItems();
        generateTitle(false);
        mClusterChanged = false;
    }
}
Example 40
Project: myrom_frameworks_policies-master  File: LockScreen.java View source code
/**
     * @return A localized format like "Fri, Sep 18, 2009"
     */
private java.text.DateFormat getLockScreenDateFormat() {
    SimpleDateFormat adjusted = null;
    try {
        // this call gives us the localized order
        final SimpleDateFormat dateFormat = (SimpleDateFormat) java.text.DateFormat.getDateInstance(java.text.DateFormat.FULL);
        adjusted = new SimpleDateFormat(dateFormat.toPattern().replace("MMMM", // we want "Sep", not "September"
        "MMM").replace("EEEE", // we want "Fri", no "Friday"
        "EEE"));
    } catch (ClassCastException e) {
        Log.e("LockScreen", "couldn't finnagle our custom date format :(", e);
        return java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM);
    }
    return adjusted;
}
Example 41
Project: fdroidclient-master  File: AppDetails.java View source code
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    java.text.DateFormat df = DateFormat.getDateFormat(context);
    final Apk apk = getItem(position);
    ViewHolder holder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.apklistitem, parent, false);
        holder = new ViewHolder();
        holder.version = (TextView) convertView.findViewById(R.id.version);
        holder.status = (TextView) convertView.findViewById(R.id.status);
        holder.repository = (TextView) convertView.findViewById(R.id.repository);
        holder.size = (TextView) convertView.findViewById(R.id.size);
        holder.api = (TextView) convertView.findViewById(R.id.api);
        holder.incompatibleReasons = (TextView) convertView.findViewById(R.id.incompatible_reasons);
        holder.buildtype = (TextView) convertView.findViewById(R.id.buildtype);
        holder.added = (TextView) convertView.findViewById(R.id.added);
        holder.nativecode = (TextView) convertView.findViewById(R.id.nativecode);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.version.setText(getString(R.string.version) + " " + apk.versionName + (apk.versionCode == app.suggestedVersionCode ? "  ☆" : ""));
    holder.status.setText(getInstalledStatus(apk));
    holder.repository.setText(getString(R.string.repo_provider, RepoProvider.Helper.findById(getContext(), apk.repo).getName()));
    if (apk.size > 0) {
        holder.size.setText(Utils.getFriendlySize(apk.size));
        holder.size.setVisibility(View.VISIBLE);
    } else {
        holder.size.setVisibility(View.GONE);
    }
    if (!Preferences.get().expertMode()) {
        holder.api.setVisibility(View.GONE);
    } else if (apk.minSdkVersion > 0 && apk.maxSdkVersion < Apk.SDK_VERSION_MAX_VALUE) {
        holder.api.setText(getString(R.string.minsdk_up_to_maxsdk, Utils.getAndroidVersionName(apk.minSdkVersion), Utils.getAndroidVersionName(apk.maxSdkVersion)));
        holder.api.setVisibility(View.VISIBLE);
    } else if (apk.minSdkVersion > 0) {
        holder.api.setText(getString(R.string.minsdk_or_later, Utils.getAndroidVersionName(apk.minSdkVersion)));
        holder.api.setVisibility(View.VISIBLE);
    } else if (apk.maxSdkVersion > 0) {
        holder.api.setText(getString(R.string.up_to_maxsdk, Utils.getAndroidVersionName(apk.maxSdkVersion)));
        holder.api.setVisibility(View.VISIBLE);
    }
    if (apk.srcname != null) {
        holder.buildtype.setText("source");
    } else {
        holder.buildtype.setText("bin");
    }
    if (apk.added != null) {
        holder.added.setText(getString(R.string.added_on, df.format(apk.added)));
        holder.added.setVisibility(View.VISIBLE);
    } else {
        holder.added.setVisibility(View.GONE);
    }
    if (Preferences.get().expertMode() && apk.nativecode != null) {
        holder.nativecode.setText(TextUtils.join(" ", apk.nativecode));
        holder.nativecode.setVisibility(View.VISIBLE);
    } else {
        holder.nativecode.setVisibility(View.GONE);
    }
    if (apk.incompatibleReasons != null) {
        holder.incompatibleReasons.setText(getResources().getString(R.string.requires_features, TextUtils.join(", ", apk.incompatibleReasons)));
        holder.incompatibleReasons.setVisibility(View.VISIBLE);
    } else {
        holder.incompatibleReasons.setVisibility(View.GONE);
    }
    // Disable it all if it isn't compatible...
    final View[] views = { convertView, holder.version, holder.status, holder.repository, holder.size, holder.api, holder.buildtype, holder.added, holder.nativecode };
    for (final View v : views) {
        v.setEnabled(apk.compatible);
    }
    return convertView;
}
Example 42
Project: android-betterpickers-master  File: RadialTimePickerDialogFragment.java View source code
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_HOUR_OF_DAY) && savedInstanceState.containsKey(KEY_MINUTE) && savedInstanceState.containsKey(KEY_IS_24_HOUR_VIEW)) {
        mInitialHourOfDay = savedInstanceState.getInt(KEY_HOUR_OF_DAY);
        mInitialMinute = savedInstanceState.getInt(KEY_MINUTE);
        mIs24HourMode = savedInstanceState.getBoolean(KEY_IS_24_HOUR_VIEW);
        mInKbMode = savedInstanceState.getBoolean(KEY_IN_KB_MODE);
        mStyleResId = savedInstanceState.getInt(KEY_STYLE);
        if (savedInstanceState.containsKey(KEY_FUTURE_MINUTES_LIMIT)) {
            mFutureMinutesLimit = savedInstanceState.getInt(KEY_FUTURE_MINUTES_LIMIT);
        }
        if (savedInstanceState.containsKey(KEY_PAST_MINUTES_LIMIT)) {
            mPastMinutesLimit = savedInstanceState.getInt(KEY_PAST_MINUTES_LIMIT);
        }
        if (savedInstanceState.containsKey(KEY_CURRENT_DATE)) {
            mValidateDateTime = (Calendar) savedInstanceState.getSerializable(KEY_CURRENT_DATE);
        }
        if (savedInstanceState.containsKey(KEY_PICKER_DATE)) {
            mPickerDate = (Calendar) savedInstanceState.getSerializable(KEY_PICKER_DATE);
        }
    } else {
        if (mIs24HourMode == null) {
            mIs24HourMode = DateFormat.is24HourFormat(getContext());
        }
    }
}
Example 43
Project: ARTPart-master  File: SimpleDateFormat.java View source code
private AttributedCharacterIterator formatToCharacterIteratorImpl(Date date) {
    StringBuffer buffer = new StringBuffer();
    ArrayList<FieldPosition> fields = new ArrayList<FieldPosition>();
    // format the date, and find fields
    formatImpl(date, buffer, null, fields);
    // create and AttributedString with the formatted buffer
    AttributedString as = new AttributedString(buffer.toString());
    // add DateFormat field attributes to the AttributedString
    for (FieldPosition pos : fields) {
        Format.Field attribute = pos.getFieldAttribute();
        as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
    }
    // return the CharacterIterator from AttributedString
    return as.getIterator();
}
Example 44
Project: anewjkuapp-master  File: WeekView.java View source code
@Override
public String interpretDate(Calendar date) {
    try {
        Locale locale = getContext().getResources().getConfiguration().locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat(DateFormat.getBestDateTimePattern(locale, "EEEEE M dd"), locale) : new SimpleDateFormat(DateFormat.getBestDateTimePattern(locale, "EEE M dd"), locale);
            return sdf.format(date.getTime()).toUpperCase();
        } else {
            SimpleDateFormat sdf = mDayNameLength == LENGTH_SHORT ? new SimpleDateFormat("EEEEE M/dd", locale) : new SimpleDateFormat("EEE M/dd", locale);
            return sdf.format(date.getTime()).toUpperCase();
        }
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    }
}