Example usage for android.content SharedPreferences getLong

List of usage examples for android.content SharedPreferences getLong

Introduction

In this page you can find the example usage for android.content SharedPreferences getLong.

Prototype

long getLong(String key, long defValue);

Source Link

Document

Retrieve a long value from the preferences.

Usage

From source file:org.connectbot.util.UpdateHelper.java

/**
 * Constructor will automatically spawn thread to check for updates.
 * Recommended usage is <code>new UpdateHelper(this);</code> in the first
 * onCreate() of your app./*w w w  .ja  va2 s  .  co  m*/
 */
public UpdateHelper(Context context) {
    this.context = context;

    try {
        // read current version information about this package
        PackageManager manager = context.getPackageManager();
        PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
        this.packageName = info.packageName;
        this.versionCode = info.versionCode;
        this.versionName = info.versionName;

    } catch (Exception e) {
        Log.e(TAG, "Couldn't find package information in PackageManager", e);
        return;
    }

    // decide if we really need to check for update
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

    String frequency;
    try {
        frequency = prefs.getString(PreferenceConstants.UPDATE, PreferenceConstants.UPDATE_DAILY);
    } catch (ClassCastException cce) {
        // Hm, somehow we got a long in there in the previous upgrades.
        frequency = PreferenceConstants.UPDATE_DAILY;
        Editor editor = prefs.edit();
        editor.putString(PreferenceConstants.UPDATE, frequency);
        editor.commit();
    }
    long lastChecked = prefs.getLong(PreferenceConstants.LAST_CHECKED, 0);
    long now = (System.currentTimeMillis() / 1000);
    long passed = now - lastChecked;

    boolean shouldCheck = false;
    if (PreferenceConstants.UPDATE_DAILY.equals(frequency)) {
        shouldCheck = (passed > 60 * 60 * 24);
    } else if (PreferenceConstants.UPDATE_WEEKLY.equals(frequency)) {
        shouldCheck = (passed > 60 * 60 * 24 * 7);
    }

    // place version information in user-agent string to be used later
    userAgent = String.format("%s/%s (%d, freq=%s, lang=%s)", packageName, versionName, versionCode, frequency,
            Locale.getDefault().getLanguage());

    if (shouldCheck) {
        // spawn thread to check for update
        // Note that this class should be marked final because a thread is started in the constructor.
        Thread updateThread = new Thread(this);
        updateThread.setName("UpdateHelper");
        updateThread.start();

        // update our last-checked time
        Editor editor = prefs.edit();
        editor.putLong(PreferenceConstants.LAST_CHECKED, now);
        editor.commit();

    }

}

From source file:com.ternup.caddisfly.fragment.DetailsFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    getActivity().setTitle(R.string.details);
    mContext = getActivity();// w  w w . ja  v  a  2s .c  om

    ListView listView = getListView();

    mFolderName = getArguments().getString(PreferencesHelper.FOLDER_NAME_KEY);

    View header = getActivity().getLayoutInflater().inflate(R.layout.fragment_result, null, false);

    mPpmText = (TextView) header.findViewById(R.id.ppmText);
    mDateView = (TextView) header.findViewById(R.id.testDate);
    mTitleView = (TextView) header.findViewById(R.id.titleView);
    mResultTextView = (TextView) header.findViewById(R.id.result);
    mAddressText = (TextView) header.findViewById(R.id.address1);
    mAddress2Text = (TextView) header.findViewById(R.id.address2);
    mAddress3Text = (TextView) header.findViewById(R.id.address3);
    mSourceText = (TextView) header.findViewById(R.id.sourceType);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);

    mFolderName = getArguments().getString(PreferencesHelper.FOLDER_NAME_KEY);
    mId = getArguments().getLong(getString(R.string.currentTestId));
    mLocationId = sharedPreferences.getLong(getString(R.string.currentLocationId), -1);

    File directory = new File(FileUtils.getStoragePath(getActivity(), mLocationId, mFolderName, false));

    long locationId = sharedPreferences.getLong(getString(R.string.currentLocationId), -1);

    final ArrayList<String> imagePaths = FileUtils.getFilePaths(getActivity(), mFolderName, "/small/",
            locationId);

    if (mId > -1) {
        if (!directory.exists()) {
            Uri uri = ContentUris.withAppendedId(TestContentProvider.CONTENT_URI, mId);
            mContext.getContentResolver().delete(uri, null, null);
            goBack();
        } else if (imagePaths.size() > 0) {
            displayResult();
        } else {
            FileUtils.deleteFolder(getActivity(), mLocationId, mFolderName);
            goBack();
        }
    }

    ListView drawerList = (ListView) getActivity().findViewById(R.id.navigation_drawer);
    drawerList.setItemChecked(-1, true);
    drawerList.setSelection(-1);

    assert listView != null;
    listView.addHeaderView(header);

    // Gradient shading for title
    assert header != null;

    //Collections.sort(imagePaths);

    GalleryListAdapter adapter = new GalleryListAdapter(getActivity(), mTestTypeId, mId, imagePaths, true);
    setListAdapter(adapter);

    Shader textShader = new LinearGradient(0, 0, 0, mTitleView.getPaint().getTextSize(),
            new int[] { getResources().getColor(R.color.textGradientStart),
                    getResources().getColor(R.color.textGradientEnd) },
            new float[] { 0, 1 }, Shader.TileMode.CLAMP);
    mTitleView.getPaint().setShader(textShader);

}

From source file:com.lastsoft.plog.adapter.GameAdapter.java

public void playPopup(View v, final int position) {

    try {//from   w ww . j a va  2s .c  o m
        InputMethodManager inputManager = (InputMethodManager) mActivity
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(mActivity.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception ignored) {
    }

    PopupMenu popup = new PopupMenu(mActivity, v);

    MenuInflater inflater = popup.getMenuInflater();

    if (games.get(position).expansionFlag == true) {
        inflater.inflate(R.menu.game_expansion_overflow, popup.getMenu());
    } else {
        inflater.inflate(R.menu.game_overflow, popup.getMenu());
    }
    if (games.get(position).gameBGGID == null || games.get(position).gameBGGID.equals("")) {
        popup.getMenu().removeItem(R.id.update_bgg);
        popup.getMenu().removeItem(R.id.open_bgg);
        popup.getMenu().removeItem(R.id.add_bgg);
    }
    if (games.get(position).gameBoxImage == null || games.get(position).gameBoxImage.equals("")) {
        popup.getMenu().removeItem(R.id.view_box_photo);
    }
    if (games.get(position).taggedToPlay <= 0) {
        popup.getMenu().removeItem(R.id.remove_bucket_list);
    } else {
        popup.getMenu().removeItem(R.id.add_bucket_list);
    }

    SharedPreferences app_preferences;
    app_preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);
    long currentDefaultPlayer = app_preferences.getLong("defaultPlayer", -1);
    if (games.get(position).collectionFlag || currentDefaultPlayer == -1) {
        popup.getMenu().removeItem(R.id.add_bgg);
    }

    //check if this game has been played
    //if so, can't delete
    if (GamesPerPlay.hasGameBeenPlayed(games.get(position))) {
        popup.getMenu().removeItem(R.id.delete_game);
    }
    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.delete_game:
                ((MainActivity) mActivity).deleteGame(games.get(position).getId());
                return true;
            case R.id.add_tenbyten:
                ((MainActivity) mActivity).addToTenXTen(games.get(position).getId());
                return true;
            case R.id.view_plays:
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 9, fragmentName,
                            currentYear);
                } else {
                    ((MainActivity) mActivity).openPlays(games.get(position).gameName, false, 0, fragmentName,
                            currentYear);
                }
                return true;
            case R.id.open_bgg:
                Intent browserIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse("http://bgg.cc/boardgame/" + games.get(position).gameBGGID));
                mActivity.startActivity(browserIntent);
                return true;
            case R.id.update_bgg:
                mPosition = position;
                if (games.get(position).expansionFlag == true) {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, true, -1);
                } else {
                    ((MainActivity) mActivity).searchGameViaBGG(games.get(position).gameName, false, false, -1);
                }
                return true;
            case R.id.add_bgg:
                mPosition = position;
                ((MainActivity) mActivity).updateGameViaBGG(games.get(position).gameName,
                        games.get(position).gameBGGID, "", true, false);
                return true;
            case R.id.add_box_photo:
                ((GamesFragment) mFragment).captureBox(games.get(position));
                return true;
            case R.id.view_box_photo:
                String[] photoParts = games.get(position).gameBoxImage.split("/");
                File newFile = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
                                + "/Plog/",
                        photoParts[photoParts.length - 1]);
                Uri contentUri = FileProvider.getUriForFile(mActivity.getApplicationContext(),
                        "com.lastsoft.plog.fileprovider", newFile);
                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_VIEW);
                intent.setDataAndType(contentUri, "image/*");
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                mActivity.startActivity(intent);
                return true;
            case R.id.add_bucket_list:
                String[] ids = TimeZone.getAvailableIDs(-5 * 60 * 60 * 1000);
                // if no ids were returned, something is wrong. get out.
                //if (ids.length == 0)
                //    System.exit(0);

                // begin output
                //System.out.println("Current Time");

                // create a Eastern Standard Time time zone
                SimpleTimeZone pdt = new SimpleTimeZone(-5 * 60 * 60 * 1000, ids[0]);

                // set up rules for daylight savings time
                pdt.setStartRule(Calendar.APRIL, 1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);
                pdt.setEndRule(Calendar.OCTOBER, -1, Calendar.SUNDAY, 2 * 60 * 60 * 1000);

                // create a GregorianCalendar with the Pacific Daylight time zone
                // and the current date and time
                Calendar calendar = new GregorianCalendar(pdt);
                Date trialTime = new Date();
                calendar.setTime(trialTime);
                int i = (int) (calendar.getTime().getTime() / 1000);
                games.get(position).taggedToPlay = i;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.added_to_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                games.get(position).taggedToPlay = 0;
                                games.get(position).save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!

                return true;
            case R.id.remove_bucket_list:
                final int taggedToPlay = games.get(position).taggedToPlay;
                final Game gameToUndo = games.get(position);
                games.get(position).taggedToPlay = 0;
                games.get(position).save();

                Snackbar.make(((GamesFragment) mFragment).mCoordinatorLayout,
                        games.get(position).gameName + mActivity.getString(R.string.removed_from_bl),
                        Snackbar.LENGTH_LONG)
                        .setAction(mActivity.getString(R.string.undo), new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                gameToUndo.taggedToPlay = taggedToPlay;
                                gameToUndo.save();
                                if (playListType == 2) {
                                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                                }
                            }
                        }).show(); // Do not forget to show!
                if (playListType == 2) {
                    ((MainActivity) mActivity).onFragmentInteraction("refresh_games");
                }
                return true;
            default:
                return false;
            }
        }
    }

    );
    popup.show();
}

From source file:com.numenta.core.service.DataSyncService.java

/**
 * This method is execute periodically and update {@link com.numenta.core.data.CoreDatabase}
 * with new data from the/*  w  ww .ja  v  a 2s .c  o m*/
 * server.
 */
protected void synchronizeWithServer() throws IOException {
    Log.i(TAG, "synchronizeWithServer");

    if (_synchronizingWithServer) {
        return;
    }
    if (!NetUtils.isConnected()) {
        // Not connected, skip until we connect
        return;
    }

    final CoreDatabase database = HTMApplication.getDatabase();
    if (database == null) {
        return;
    }
    synchronized (this) {
        if (_synchronizingWithServer) {
            return;
        }
        _synchronizingWithServer = true;
    }
    String result = null;
    try {
        // Guard against blocking the UI Thread
        if (Looper.myLooper() == Looper.getMainLooper()) {
            throw new IllegalStateException("You should not access the database from the UI thread");
        }

        fireRefreshStateEvent(_synchronizingWithServer);

        final Context context = _service.getApplicationContext();
        final long now = System.currentTimeMillis();

        // Check if enough time has passed since we checked for new data
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        final long lastConnectedTime = prefs.getLong(PREF_LAST_CONNECTED_TIME, 0);
        if (now - lastConnectedTime < DataUtils.METRIC_DATA_INTERVAL) {
            return;
        }

        // Calculate hours since last update. This information will be
        // passed to the user together with error message
        final CharSequence hoursSinceData = DateUtils.getRelativeTimeSpanString(database.getLastTimestamp(),
                now, DateUtils.MINUTE_IN_MILLIS);

        Future<?> pendingIO = null;
        try {
            // Try to connect to server
            if (_htmClient == null) {
                _htmClient = _service.connectToServer();
            }
            if (_htmClient == null) {
                throw new IOException("Unable to connect to server");
            }

            // Update last connected time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong(PREF_LAST_CONNECTED_TIME, now);
            editor.apply();

            // Start by downloading all the metrics available from backend
            // in a background IO thread
            pendingIO = _service.getIOThreadPool().submit(new Callable<Void>() {
                @Override
                public Void call() throws Exception {

                    try {
                        // First load metrics
                        loadAllMetrics();

                        // Load all annotations after metrics
                        loadAllAnnotations();

                        // Load all data after annotations
                        loadAllData();

                        // Synchronize notifications after data
                        synchronizeNotifications();

                        // Synchronize application data last
                        HTMApplication.getInstance().loadApplicationData(_htmClient);

                    } catch (android.database.sqlite.SQLiteFullException e) {
                        // Try to delete old records to make room if possible
                        Log.e(TAG, "Failed to save data into database", e);
                        database.deleteOldRecords();
                    }
                    return null;
                }
            });
            // Wait for metric data to finish
            pendingIO.get();
        } catch (InterruptedException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Log.w(TAG, "Interrupted while loading data");
        } catch (ExecutionException e) {
            // Cancel pending tasks
            if (!pendingIO.isDone()) {
                pendingIO.cancel(true);
            }
            Throwable original = e.getCause();
            if (original instanceof AuthenticationException) {
                _service.fireAuthenticationFailedEvent();
            } else if (original instanceof ObjectNotFoundException) {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            } else if (original instanceof IOException) {
                Log.e(TAG, "Unable to connect", e);
                result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
            } else {
                Log.e(TAG, "Error loading data", e);
                result = context.getString(R.string.refresh_update_error, hoursSinceData);
            }
        } catch (AuthenticationException e) {
            _service.fireAuthenticationFailedEvent();
        } catch (HTMException e) {
            Log.e(TAG, "Error loading data", e);
            result = context.getString(R.string.refresh_update_error, hoursSinceData);
        } catch (IOException e) {
            Log.e(TAG, "Unable to connect", e);
            result = context.getString(R.string.refresh_server_unreachable, hoursSinceData);
        }
    } finally {
        _synchronizingWithServer = false;
        fireRefreshStateEvent(_synchronizingWithServer, result);
    }
}

From source file:dess15proj5.fau.cs.osr_amos.mobiletimerecording.ui.SelectedProjectFragment.java

/**
 * This method is called in the android lifecycle when the application is resumed.
 *
 * methodtype command method//from   w  ww.  j a  va2s . c o m
 */
@Override
public void onResume() {
    super.onResume();

    addSessionsToAdapter();

    SharedPreferences sharedPref = getActivity().getSharedPreferences("selectedProject", Context.MODE_PRIVATE);
    boolean isRecording = sharedPref.getBoolean("isRecording", false);
    if (isRecording) {
        long sessionId = sharedPref.getLong("sessionId", 0L);
        try {
            SessionsDAO sessionsDAO = DataAccessObjectFactory.getInstance().createSessionsDAO(getActivity());
            session = sessionsDAO.load(sessionId);
            Date startTime = session.getStartTime();
            Date stopTime = session.getStopTime();
            if (startTime.equals(stopTime)) {
                startStopBtn.setImageDrawable(
                        ContextCompat.getDrawable(getActivity(), R.drawable.ic_stop_white_24dp));
                long elapsedRealTimeOffset = System.currentTimeMillis() - SystemClock.elapsedRealtime();
                Long difference = startTime.getTime() - elapsedRealTimeOffset;
                timer.start();
                timer.setBase(difference);
            }
        } catch (CursorIndexOutOfBoundsException e) {
            Toast.makeText(getActivity(), "Could not load session due to database errors!", Toast.LENGTH_LONG)
                    .show();
        } catch (SQLException e) {
            Toast.makeText(getActivity(), "Could not load session due to database errors!", Toast.LENGTH_LONG)
                    .show();
        }
    }
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {// w w  w .  j ava 2 s .  c  o  m

    Context context = getContext();

    App.getApiManager().getEarthquakeService().getData().enqueue(new Callback<EarthquakeObject>() {
        @Override
        public void onResponse(Call<EarthquakeObject> call, Response<EarthquakeObject> response) {
            EarthquakeObject earthquake = response.body();

            Vector<ContentValues> cVVector = new Vector<>(earthquake.getFeatures().size());

            double currentBiggest = 0.0;
            ContentValues notifyValues = null;

            for (Feature each : earthquake.getFeatures()) {

                ContentValues earthquakeValues = new ContentValues();

                earthquakeValues.put(EarthquakeColumns.PLACE, each.getProperties().getPlace());
                earthquakeValues.put(EarthquakeColumns.ID_EARTH, each.getId());
                earthquakeValues.put(EarthquakeColumns.MAG, each.getProperties().getMag());
                earthquakeValues.put(EarthquakeColumns.TYPE, each.getProperties().getType());
                earthquakeValues.put(EarthquakeColumns.ALERT, each.getProperties().getAlert());
                earthquakeValues.put(EarthquakeColumns.TIME, each.getProperties().getTime());
                earthquakeValues.put(EarthquakeColumns.URL, each.getProperties().getUrl());
                earthquakeValues.put(EarthquakeColumns.DETAIL, each.getProperties().getDetail());
                earthquakeValues.put(EarthquakeColumns.DEPTH, each.getGeometry().getCoordinates().get(2));
                earthquakeValues.put(EarthquakeColumns.LONGITUDE, each.getGeometry().getCoordinates().get(0));
                earthquakeValues.put(EarthquakeColumns.LATITUDE, each.getGeometry().getCoordinates().get(1));

                LatLng latLng = new LatLng(each.getGeometry().getCoordinates().get(1),
                        each.getGeometry().getCoordinates().get(0));
                LatLng location = LocationUtils.getLocation(context);
                earthquakeValues.put(EarthquakeColumns.DISTANCE, LocationUtils.getDistance(latLng, location));

                cVVector.add(earthquakeValues);

                if (each.getProperties().getMag() != null && each.getProperties().getMag() > currentBiggest) {
                    currentBiggest = each.getProperties().getMag();
                    notifyValues = new ContentValues(earthquakeValues);
                    notifyValues.put(EarthquakeColumns.PLACE,
                            Utilities.formatEarthquakePlace(each.getProperties().getPlace()));
                }
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = context.getContentResolver();

            if (cVVector.size() > 0) {
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(EarthquakeColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus one to delete old data from the database
            Date date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS);

            int deleted = resolver.delete(EarthquakeColumns.CONTENT_URI, EarthquakeColumns.TIME + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
            Log.v(TAG, "Service Complete. " + inserted + " Inserted, " + deleted + " deleted");
            sendNotification(notifyValues);
        }

        @Override
        public void onFailure(Call<EarthquakeObject> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    App.getNewsManager().getNewsService().getNews().enqueue(new Callback<Rss>() {
        @Override
        public void onResponse(Call<Rss> call, Response<Rss> response) {
            Channel news = response.body().getChannel();

            Vector<ContentValues> cVVector = new Vector<>(news.getItem().size());

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z",
                    Locale.getDefault());
            Date date = new Date();

            for (Item each : news.getItem()) {

                ContentValues weatherValues = new ContentValues();

                try {
                    date = simpleDateFormat.parse(each.getPubDate());
                } catch (ParseException e) {
                    Log.e(TAG, "e:" + e);
                }

                weatherValues.put(NewsColumns.DATE, date.getTime());
                weatherValues.put(NewsColumns.TITLE, each.getTitle());
                weatherValues.put(NewsColumns.DESCRIPTION,
                        Html.toHtml(new SpannedString(each.getDescription())));
                weatherValues.put(NewsColumns.URL, each.getLink());
                weatherValues.put(NewsColumns.GUID, each.getGuid().getContent());

                cVVector.add(weatherValues);
            }

            int inserted = 0;
            // add to database
            ContentResolver resolver = getContext().getContentResolver();

            if (cVVector.size() > 0) {

                // Student: call bulkInsert to add the weatherEntries to the database here
                ContentValues[] cvArray = new ContentValues[cVVector.size()];
                cVVector.toArray(cvArray);
                inserted = resolver.bulkInsert(NewsColumns.CONTENT_URI, cvArray);
            }

            // Set the date to day minus two to delete old data from the database
            date = new Date();
            date.setTime(date.getTime() - DateUtils.DAY_IN_MILLIS * 3);

            int deleted = resolver.delete(NewsColumns.CONTENT_URI, NewsColumns.DATE + " <= ?",
                    new String[] { String.valueOf(date.getTime()) });
        }

        @Override
        public void onFailure(Call<Rss> call, Throwable t) {
            Log.e(TAG, "onFailure: " + t.toString());
        }
    });

    // TODO: 4/22/16 possible refactoring 
    //checking the last update and notify if it' the first of the day
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    String lastNotificationKey = context.getString(R.string.sharedprefs_key_last_countupdate);
    long lastSync = prefs.getLong(lastNotificationKey, DateUtils.DAY_IN_MILLIS);

    if (System.currentTimeMillis() - lastSync >= Utilities.getSyncIntervalPrefs(context)
            * DateUtils.SECOND_IN_MILLIS) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
        Date date = new Date(System.currentTimeMillis());

        String startTime[] = new String[] { simpleDateFormat.format(date.getTime() - DateUtils.YEAR_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS * 30),
                simpleDateFormat.format(date.getTime() - DateUtils.WEEK_IN_MILLIS),
                simpleDateFormat.format(date.getTime() - DateUtils.DAY_IN_MILLIS) };

        String endTime = simpleDateFormat.format(date);

        int iterator = 1;
        while (iterator < CountColumns.ALL_COLUMNS.length) {
            final int round = iterator;

            App.getApiManager().getEarthquakeService().getEarthquakeStats(startTime[round - 1], endTime)
                    .enqueue(new Callback<CountEarthquakes>() {
                        @Override
                        public void onResponse(Call<CountEarthquakes> call,
                                Response<CountEarthquakes> response) {
                            ContentValues count = new ContentValues();
                            count.put(CountColumns.ALL_COLUMNS[round], response.body().getCount());

                            ContentResolver contentResolver = context.getContentResolver();

                            Cursor cursor = contentResolver.query(CountColumns.CONTENT_URI, null, null, null,
                                    null);

                            if (cursor != null) {
                                if (cursor.getCount() < 1) {
                                    long inserted = ContentUris
                                            .parseId(contentResolver.insert(CountColumns.CONTENT_URI, count));
                                    //Log.d(TAG, "inserted:" + inserted);
                                } else {
                                    int updated = contentResolver.update(CountColumns.CONTENT_URI, count,
                                            CountColumns._ID + " = ?", new String[] { "1" });
                                    //Log.d(TAG, "updated: " + updated);
                                }
                                cursor.close();
                            }

                        }

                        @Override
                        public void onFailure(Call<CountEarthquakes> call, Throwable t) {
                            Log.e(TAG, "Error: " + t);
                        }
                    });
            iterator++;
        }

        //refreshing last sync
        prefs.edit().putLong(lastNotificationKey, System.currentTimeMillis()).apply();
    }

    // notify PagerActivity that data has been updated
    context.getContentResolver().notifyChange(EarthquakeColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(NewsColumns.CONTENT_URI, null, false);
    context.getContentResolver().notifyChange(CountColumns.CONTENT_URI, null, false);

    updateWidgets();
}

From source file:gsoc.google.com.byop.utils.PW.UrlDeviceDiscoveryService.java

private void restoreCache() {
    // Make sure we are trying to load the right version of the cache
    String preferencesKey = getString(R.string.discovery_service_prefs_key);
    SharedPreferences prefs = getSharedPreferences(preferencesKey, Context.MODE_PRIVATE);
    int prefsVersion = prefs.getInt(PREFS_VERSION_KEY, 0);
    long now = new Date().getTime();
    if (prefsVersion != PREFS_VERSION) {
        mScanStartTime = now;// www  .  j a  va  2s . c om
        return;
    }

    // Don't load the cache if it's stale
    mScanStartTime = prefs.getLong(SCAN_START_TIME_KEY, 0);
    if (now - mScanStartTime >= SCAN_STALE_TIME_MILLIS) {
        mScanStartTime = now;
        return;
    }

    // Restore the cached metadata
    try {
        JSONObject serializedCollection = new JSONObject(prefs.getString(PW_COLLECTION_KEY, null));
        mPwCollection = PhysicalWebCollection.jsonDeserialize(serializedCollection);
    } catch (JSONException e) {
        Log.e(TAG, "Can't restore Physical Web collection cache", e);
    } catch (PhysicalWebCollectionException e) {
        Log.e(TAG, "Could not restore Physical Web collection cache", e);
    }
}

From source file:com.gsoc.ijosa.liquidgalaxycontroller.PW.UrlDeviceDiscoveryService.java

private void restoreCache() {
    // Make sure we are trying to load the right version of the cache
    String preferencesKey = getString(R.string.discovery_service_prefs_key);
    SharedPreferences prefs = getSharedPreferences(preferencesKey, Context.MODE_PRIVATE);
    int prefsVersion = prefs.getInt(PREFS_VERSION_KEY, 0);
    long now = new Date().getTime();
    if (prefsVersion != PREFS_VERSION) {
        mScanStartTime = now;/*from  w w w  .  jav a 2  s .c o m*/
        return;
    }

    // Don't load the cache if it's stale
    mScanStartTime = prefs.getLong(SCAN_START_TIME_KEY, 0);
    if (now - mScanStartTime >= SCAN_STALE_TIME_MILLIS) {
        mScanStartTime = now;
        return;
    }

    // Restore the cached metadata
    try {
        JSONObject serializedCollection = new JSONObject(prefs.getString(PW_COLLECTION_KEY, null));
        mPwCollection = PhysicalWebCollection.jsonDeserialize(serializedCollection);
    } catch (JSONException e) {
        Log.e(TAG, "Could not restore collection cache", e);
    } catch (PhysicalWebCollectionException e) {
        Log.e(TAG, "Could not restore collection cache", e);
    }
}

From source file:com.jtechme.apphub.UpdateService.java

/**
 * Check whether it is time to run the scheduled update.
 * We don't want to run if://  w  w  w  .jav  a  2  s.c o  m
 * - The time between scheduled runs is set to zero (though don't know
 * when that would occur)
 * - Last update was too recent
 * - Not on wifi, but the property for "Only auto update on wifi" is set.
 *
 * @return True if we are due for a scheduled update.
 */
private boolean verifyIsTimeForScheduledRun() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    String sint = prefs.getString(Preferences.PREF_UPD_INTERVAL, "0");
    int interval = Integer.parseInt(sint);
    if (interval == 0) {
        Log.i(TAG, "Skipping update - disabled");
        return false;
    }
    long lastUpdate = prefs.getLong(Preferences.PREF_UPD_LAST, 0);
    long elapsed = System.currentTimeMillis() - lastUpdate;
    if (elapsed < interval * 60 * 60 * 1000) {
        Log.i(TAG, "Skipping update - done " + elapsed + "ms ago, interval is " + interval + " hours");
        return false;
    }

    return isNetworkAvailableForUpdate(this);
}

From source file:org.iota.wallet.ui.fragment.NewTransferFragment.java

@OnClick(R.id.new_transfer_send_fab_button)
public void onNewTransferSendFabClick(FloatingActionButton fab) {
    inputManager.hideSoftInputFromWindow(fab.getWindowToken(), 0);

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

    addressEditTextInputLayout.setError(null);
    amountEditTextInputLayout.setError(null);

    //noinspection StatementWithEmptyBody
    if (!isValidAddress()) {

    } else if (getAmount().isEmpty() || getAmount().equals("0")) {
        amountEditTextInputLayout.setError(getString(R.string.messages_enter_amount));

    } else if (prefs.getLong(Constants.PREFERENCES_CURRENT_IOTA_BALANCE, 0) < Long
            .parseLong(amountInSelectedUnit())) {
        amountEditTextInputLayout.setError(getString(R.string.messages_not_enough_balance));

    } else {//from w  w w  . ja va  2 s.c om
        AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                .setMessage(R.string.message_confirm_transfer).setCancelable(false)
                .setPositiveButton(R.string.buttons_ok, null).setNegativeButton(R.string.buttons_cancel, null)
                .create();

        alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.buttons_ok),
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        SendTransferRequest tir = new SendTransferRequest(getAddress(), amountInSelectedUnit(),
                                getMessage(), getTaG());

                        TaskManager rt = new TaskManager(getActivity());
                        rt.startNewRequestTask(tir);

                        getActivity().onBackPressed();
                    }
                });

        alertDialog.show();
    }
}