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:eu.liveGov.gordexola.urbanplanning.activities.MainActivity.java

@Override
public void anonymousUpdated() {

    logger.info("anonymousUpdated");
    PermissionHelper.addListener(this);

    if (_savedInstanceState == null) {
        new LogFileHelper().postLogFile(getApplicationContext());
        Time now = new Time();
        now.setToNow();/*from w ww.  j a  va2  s  .c  o m*/
        logger.info("Starting the application... ({})", now.format3339(false));
        PermissionHelper ph = PermissionHelper.getInstance();
        ph.downloadPermissions(getBaseContext());

    } else {
        if (!PermissionHelper.isDownloading()) {
            loadFragmentsWithPermissions("startupApp");
        }
    }
    _savedInstanceState = null; // we don't need it anymore.

    if (pbarGeneral != null)
        pbarGeneral.setProgress(2);

}

From source file:com.code44.finance.ui.dialogs.recurrencepicker.RecurrencePickerDialogFragment.java

static private void copyEventRecurrenceToModel(final EventRecurrence er, RecurrenceModel model) {
    // Freq://from w ww.jav a 2 s  . c  o  m
    switch (er.freq) {
    case EventRecurrence.ONCE:
        model.freq = RecurrenceModel.FREQ_ONCE;
        model.recurrenceState = RecurrenceModel.STATE_NO_RECURRENCE;
        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");
        }
    }
}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.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>/*from www  .jav a2  s .co 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<>(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.

        GregorianCalendar calendar = new GregorianCalendar();
        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(WeatherEntry.COLUMN_LOC_KEY, locationId);
            weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime);
            weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity);
            weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure);
            weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed);
            weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection);
            weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high);
            weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low);
            weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description);
            weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId);

            cVVector.add(weatherValues);
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            // Student: call bulkInsert to add the weatherEntries to the database here
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);

            ContentResolver contentResolver = getContext().getContentResolver();
            inserted = contentResolver.bulkInsert(WeatherEntry.CONTENT_URI, cvArray);
            contentResolver.delete(WeatherEntry.CONTENT_URI, WeatherEntry.COLUMN_DATE + "<= " + "?",
                    new String[] { Long.toString(dayTime.setJulianDay(julianStartDay - 1)) });

            notifyWeather();
        }
        Log.d(TAG, "getWeatherDataFromJson: " + inserted + " inserted");
    } catch (JSONException e) {
        Log.e(TAG, e.getMessage(), e);
        e.printStackTrace();
    }
}

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

/**
 * Returns a string representation for the time, with a relative date and an absolute time
 *//*from   ww  w.ja va2  s . c  om*/
public static String formatTime(Context context, Time time) {
    Time now = new Time();
    now.setToNow();
    String dateString;
    if (time.allDay) {
        Time allDayNow = new Time("UTC");
        allDayNow.set(now.monthDay, now.month, now.year);
        dateString = DateUtils.getRelativeTimeSpanString(time.toMillis(false), allDayNow.toMillis(false),
                DateUtils.DAY_IN_MILLIS).toString();
    } else {
        dateString = DateUtils
                .getRelativeTimeSpanString(time.toMillis(false), now.toMillis(false), DateUtils.DAY_IN_MILLIS)
                .toString();
    }

    // return combined date and time
    String timeString = new DateFormatter(context).format(time, DateFormatContext.NOTIFICATION_VIEW_TIME);
    return new StringBuilder().append(dateString).append(", ").append(timeString).toString();
}

From source file:com.android.calendar.alerts.AlertService.java

private static long getNextRefreshTime(NotificationInfo info, long currentTime) {
    long startAdjustedForAllDay = info.startMillis;
    long endAdjustedForAllDay = info.endMillis;
    if (info.allDay) {
        Time t = new Time();
        startAdjustedForAllDay = Utils.convertAlldayUtcToLocal(t, info.startMillis, Time.getCurrentTimezone());
        endAdjustedForAllDay = Utils.convertAlldayUtcToLocal(t, info.startMillis, Time.getCurrentTimezone());
    }// w w  w.j a  va  2s  . c  o  m

    // We change an event's priority bucket at 15 minutes into the event or 1/4 event duration.
    long nextRefreshTime = Long.MAX_VALUE;
    long gracePeriodCutoff = startAdjustedForAllDay
            + getGracePeriodMs(startAdjustedForAllDay, endAdjustedForAllDay, info.allDay);
    if (gracePeriodCutoff > currentTime) {
        nextRefreshTime = Math.min(nextRefreshTime, gracePeriodCutoff);
    }

    // ... and at the end (so expiring ones drop into a digest).
    if (endAdjustedForAllDay > currentTime && endAdjustedForAllDay > gracePeriodCutoff) {
        nextRefreshTime = Math.min(nextRefreshTime, endAdjustedForAllDay);
    }
    return nextRefreshTime;
}

From source file:com.dgsd.android.ShiftTracker.Fragment.EditShiftFragment.java

public Shift getShift() {
    Shift shift = new Shift();

    shift.id = mInitialShift == null ? -1 : mInitialShift.id;
    shift.name = mName.getText() == null ? null : mName.getText().toString();
    shift.note = mNotes.getText() == null ? null : mNotes.getText().toString();
    shift.julianDay = mStartDate.getTag() == null ? -1 : (Integer) mStartDate.getTag();
    shift.endJulianDay = mEndDate.getTag() == null ? shift.julianDay : (Integer) mEndDate.getTag();
    shift.setStartTime(mStartTime.getTag() == null ? -1 : (Long) mStartTime.getTag());
    shift.setEndTime(mEndTime.getTag() == null ? -1 : (Long) mEndTime.getTag());
    shift.isTemplate = mSaveAsTemplate.isChecked();
    shift.reminder = Integer.valueOf(mRemindersValues[getSelectedPosition(mReminders)]);

    Time time = new Time();

    try {//  w w w . ja v a 2 s .c  o  m
        CharSequence breakDuration = mUnpaidBreak.getText();
        if (!TextUtils.isEmpty(breakDuration))
            shift.breakDuration = Integer.valueOf(breakDuration.toString());
    } catch (NumberFormatException e) {
        shift.breakDuration = -1;
    }

    try {
        CharSequence payRate = mPayRate.getText();
        if (!TextUtils.isEmpty(payRate))
            shift.payRate = Float.valueOf(payRate.toString());
    } catch (NumberFormatException e) {
        shift.breakDuration = -1;
    }

    return shift;
}

From source file:com.jogden.spunkycharts.traditionalchart.TraditionalChartFragmentAdapter.java

@Override
public void bridge(DataClientInterface dataClient, DataConsumerInterface.InsertCallback iCallback) {
    _updateReady.set(false);/*from w ww.j  a  va 2  s .c  o m*/
    iCallback.clear(_symbol, (DataConsumerInterface) this);

    Pair<OHLC[], Time> pricePair = dataClient.getBulk(_symbol, null, DataClientLocalDebug.DATA_PRICE_DEF);
    Pair<Integer[], Time> volPair = dataClient.getBulk(_symbol, null, DataClientLocalDebug.DATA_VOL_DEF);

    final OHLC[] prices = pricePair.first;
    final Integer[] vols = volPair.first;
    int len = vols.length;
    if (prices.length != len)
        throw new IllegalStateException("price / volume getBulk size inconconsistency");

    _updateTime.set(pricePair.second);
    --len;
    long endMs = _updateTime.toMillis(true);
    endMs /= GMS;
    endMs *= GMS;
    List<ContentValues> valsList = new ArrayList<ContentValues>();
    Time t = new Time();
    for (int i = 0; i < len; ++i) {
        t.set(endMs - ((len - i) * GMS));
        valsList.add(_createContentValues(prices[i], vols[i], t)); /*
                                                                   Log.d("Data-Consumer-Get-Bulk", 
                                                                   prices[i].toString() +"   " +
                                                                   String.valueOf(vols[i]) + "   " + 
                                                                   t.format("%H:%M:%S")); */
    }

    final long fEndMs = endMs;
    final int lastIndx = len;
    (new Thread() {
        public void run() {
            final int INCR = ApplicationPreferences.getTimeoutIncrement();
            /* THIS HAS TO WAIT FOR POPULATE */
            while (!_streamReady.get())
                try {
                    Thread.sleep(INCR);
                } catch (InterruptedException e) {
                }
            /* INITIALIZE OUR CACHE VALUES */
            OHLC price = prices[lastIndx];
            _lastPriceSeg.close = price.close;
            if (price.high > _lastPriceSeg.high)
                _lastPriceSeg.high = price.high;
            if (price.low < _lastPriceSeg.low)
                _lastPriceSeg.low = price.low;
            _lastVolSeg += vols[lastIndx];
            _lastGranularPriceSeg = new OHLC(price);
            _lastGranularVolSeg = vols[lastIndx];
            _lastGranularSegTime.set(fEndMs);
            _updateReady.set(true);
        }
    }).start();

    iCallback.insertRows(valsList, _symbol, (DataConsumerInterface) this);

}

From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java

private boolean isTaskChangedAfter(OpencrxTaskContainer task, OpencrxTaskContainer task2) {
    Time modTime = new Time();
    modTime.set(task.task.getValue(Task.MODIFICATION_DATE));

    Time time = new Time();
    time.set(task2.task.getValue(Task.MODIFICATION_DATE));

    return modTime.after(time);
}

From source file:cw.kop.autobackground.settings.WearSettingsFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    final DisplayMetrics displayMetrics = getResources().getDisplayMetrics();

    View view;/*  w  w w  .j a  v a2  s.  c  o m*/

    if (displayMetrics.widthPixels > displayMetrics.heightPixels) {
        view = inflater.inflate(R.layout.wear_settings_layout_landscape, container, false);
        watchContainer = (RelativeLayout) view.findViewById(R.id.watch_face_container);
        watchContainer.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {

                        int height = watchBackground.getHeight();
                        ViewGroup.LayoutParams watchContainerParams = watchContainer.getLayoutParams();
                        watchContainerParams.height = height;
                        watchContainerParams.width = height;
                        watchContainer.setLayoutParams(watchContainerParams);
                        watchContainer.setPadding(Math.round(height * 0.278f), Math.round(height * 0.23f),
                                Math.round(height * 0.278f), Math.round(height * 0.33f));
                        watchContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        redraw();
                    }
                });
        watchContainer.setOnClickListener(this);
        watchBackground = (ImageView) view.findViewById(R.id.watch_face_background);
        watchBackground.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (getView() == null) {
                            return;
                        }
                        ViewGroup.LayoutParams watchContainerParams = watchBackground.getLayoutParams();
                        watchContainerParams.width = watchBackground.getHeight();
                        watchBackground.setLayoutParams(watchContainerParams);
                        watchBackground.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                });
    } else {
        view = inflater.inflate(R.layout.wear_settings_layout, container, false);
        watchContainer = (RelativeLayout) view.findViewById(R.id.watch_face_container);
        watchContainer.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        int width = displayMetrics.widthPixels;
                        ViewGroup.LayoutParams watchContainerParams = watchContainer.getLayoutParams();
                        watchContainerParams.height = width;
                        watchContainerParams.width = width;
                        watchContainer.setLayoutParams(watchContainerParams);
                        watchContainer.setPadding(Math.round(width * 0.278f), Math.round(width * 0.23f),
                                Math.round(width * 0.278f), Math.round(width * 0.33f));
                        watchContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        redraw();
                    }
                });
        watchContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                preferenceList.setVisibility(View.VISIBLE);
                recyclerView.setAdapter(null);
                recyclerView.setVisibility(View.GONE);
            }
        });
        watchBackground = (ImageView) view.findViewById(R.id.watch_face_background);
        watchBackground.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (getView() == null) {
                            return;
                        }
                        ViewGroup.LayoutParams watchContainerParams = watchBackground.getLayoutParams();
                        watchContainerParams.height = watchBackground.getWidth();
                        watchBackground.setLayoutParams(watchContainerParams);
                        watchBackground.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                    }
                });
    }

    surfaceView = (SurfaceView) view.findViewById(R.id.surface_view);
    //        surfaceView.setZOrderOnTop(true);
    surfaceView.setOnClickListener(this);
    surfaceView.setOnTouchListener(this);
    SurfaceHolder holder = surfaceView.getHolder();
    holder.addCallback(new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            loadImageFile();
            redraw();
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            loadImageFile();
            redraw();
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {

        }
    });

    recyclerView = (RecyclerView) view.findViewById(R.id.watch_options_list);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    preferenceList = (ListView) view.findViewById(android.R.id.list);

    Button syncButton = (Button) view.findViewById(R.id.sync_button);
    syncButton.setText("Sync Settings");
    syncButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "syncButton pressed");
            syncSettings();
        }
    });

    //        findPreference("wear_time_type").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
    //            @Override
    //            public boolean onPreferenceClick(Preference preference) {
    //
    //                DialogFactory.ListDialogListener listDialogListener = new DialogFactory.ListDialogListener() {
    //                    @Override
    //                    public void onItemClick(AdapterView<?> parent,
    //                            View view,
    //                            int position,
    //                            long id) {
    //
    //                        switch (position) {
    //                            case 0:
    //                                AppSettings.setTimeType(AppSettings.DIGITAL);
    //                                recyclerView.setAdapter(null);
    //                                preferenceList.setVisibility(View.VISIBLE);
    //                                recyclerView.setVisibility(View.GONE);
    //                                redraw();
    //                                break;
    //                            case 1:
    //                                AppSettings.setTimeType(AppSettings.ANALOG);
    //                                recyclerView.setAdapter(null);
    //                                preferenceList.setVisibility(View.VISIBLE);
    //                                recyclerView.setVisibility(View.GONE);
    //                                redraw();
    //                                break;
    //                        }
    //                        dismissDialog();
    //                    }
    //                };
    //
    //                DialogFactory.showListDialog(appContext,
    //                        "Watch face",
    //                        listDialogListener,
    //                        R.array.wear_time_types);
    //                return true;
    //            }
    //        });

    findPreference("wear_time_adjust").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {

            DialogFactory.TimeDialogListener listener = new DialogFactory.TimeDialogListener() {

                @Override
                public void onTimeSet(TimePicker view, int hour, int minute) {
                    Time time = new Time();
                    time.setToNow();
                    long offset = (hour - time.hour) * 3600000 + (minute - time.minute) * 60000;

                    Log.i(TAG, "Time offset set: " + offset);
                    AppSettings.setTimeOffset(offset);
                    this.dismissDialog();
                    redraw();
                }
            };

            DialogFactory.showTimeDialog(appContext, "Enter time", listener, -1, -1);

            return true;
        }
    });

    return view;
}

From source file:org.tomdroid.sync.web.SnowySyncService.java

public void deleteAllNotes() {

    TLog.v(TAG, "Deleting Snowy notes");

    final String userRef = Preferences.getString(Preferences.Key.SYNC_SERVER_USER_API);

    final long newRevision;

    if (latestLocalRevision > latestRemoteRevision)
        newRevision = latestLocalRevision + 1;
    else/*from   ww  w. j  a  v  a  2  s  .com*/
        newRevision = latestRemoteRevision + 1;

    syncInThread(new Runnable() {

        public void run() {

            OAuthConnection auth = getAuthConnection();

            try {
                TLog.v(TAG, "contacting " + userRef);
                String rawResponse = auth.get(userRef);
                if (rawResponse == null) {
                    return;
                }
                try {
                    JSONObject response = new JSONObject(rawResponse);
                    String notesUrl = response.getJSONObject("notes-ref").getString("api-ref");

                    TLog.v(TAG, "contacting " + notesUrl);
                    response = new JSONObject(auth.get(notesUrl));

                    JSONArray notes = response.getJSONArray("notes");
                    setSyncProgress(50);

                    TLog.v(TAG, "number of notes: {0}", notes.length());

                    ArrayList<String> guidList = new ArrayList<String>();

                    for (int i = 0; i < notes.length(); i++) {
                        JSONObject ajnote = notes.getJSONObject(i);
                        guidList.add(ajnote.getString("guid"));
                    }

                    TLog.v(TAG, "creating JSON");

                    JSONObject data = new JSONObject();
                    data.put("latest-sync-revision", newRevision);
                    JSONArray Jnotes = new JSONArray();
                    for (String guid : guidList) {
                        JSONObject Jnote = new JSONObject();
                        Jnote.put("guid", guid);
                        Jnote.put("command", "delete");
                        Jnotes.put(Jnote);
                    }
                    data.put("note-changes", Jnotes);

                    response = new JSONObject(auth.put(notesUrl, data.toString()));

                    TLog.v(TAG, "delete response: {0}", response.toString());

                    // reset latest sync date so we can push our notes again

                    latestRemoteRevision = (int) response.getLong("latest-sync-revision");
                    Preferences.putLong(Preferences.Key.LATEST_SYNC_REVISION, latestRemoteRevision);
                    Preferences.putString(Preferences.Key.LATEST_SYNC_DATE, new Time().format3339(false));

                } catch (JSONException e) {
                    TLog.e(TAG, e, "Problem parsing the server response");
                    sendMessage(PARSING_FAILED,
                            ErrorList.createErrorWithContents("JSON parsing", "json", e, rawResponse));
                    setSyncProgress(100);
                    return;
                }
            } catch (java.net.UnknownHostException e) {
                TLog.e(TAG, "Internet connection not available");
                sendMessage(NO_INTERNET);
                setSyncProgress(100);
                return;
            }
            sendMessage(REMOTE_NOTES_DELETED);
        }
    });
}