Example usage for android.content SharedPreferences getInt

List of usage examples for android.content SharedPreferences getInt

Introduction

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

Prototype

int getInt(String key, int defValue);

Source Link

Document

Retrieve an int value from the preferences.

Usage

From source file:com.aujur.ebookreader.Configuration.java

public int getLastIndex(String fileName) {

    SharedPreferences bookPrefs = getPrefsForBook(fileName);

    int pos = bookPrefs.getInt(KEY_IDX, -1);

    if (pos != -1) {
        return pos;
    }/*from  w  ww .  j av a 2s.  c  om*/

    // Fall-backs to older setting in central file
    String bookHash = Integer.toHexString(fileName.hashCode());

    pos = settings.getInt(KEY_IDX + bookHash, -1);

    if (pos != -1) {
        return pos;
    }

    // Fall-back for even older settings.
    return settings.getInt(KEY_IDX + fileName, -1);
}

From source file:com.android.talkbacktests.TestController.java

public void init(Context context) throws Exception {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final JSONObject testJson = JsonUtils.readFromRawFile(context, R.raw.test);
    final JSONArray tests = JsonUtils.getJsonArray(testJson, JSON_KEY_TESTS);
    if (tests == null || tests.length() == 0) {
        mTestSessions = new TestSession[0];
    } else {//from  w  ww . j  a  v a 2s .  co  m
        final int testCount = tests.length();
        mTestSessions = new TestSession[testCount];
        for (int i = 0; i < testCount; i++) {
            final JSONObject test = tests.getJSONObject(i);
            mTestSessions[i] = new TestSession(context, test, i);
            mTestSessions[i].setAccessCount(prefs.getInt(PREF_KEY_PREFIX_COUNT + i, 0));
            mTestSessions[i].setLastAccessTime(prefs.getLong(PREF_KEY_PREFIX_TIME + i, 0L));
        }
    }
    mOrderType = prefs.getInt(PREF_KEY_ORDER_TYPE, ORDER_DEFAULT);
    mKeyword = null;
    mTestSessionsOrderedFiltered = new ArrayList<>(mTestSessions.length);
    refreshData();
}

From source file:mobile.tiis.appv2.LoginActivity.java

private void getSavedConfigurations() {
    SharedPreferences prefs = getSharedPreferences(Constants.CONFIG, MODE_PRIVATE);
    Constants.LimitNumberOfDaysBeforeExpireVal = prefs.getInt(Constants.LimitNumberOfDaysBeforeExpire, 30);
    Constants.EligibleForVaccinationVal = prefs.getInt(Constants.EligibleForVaccination, 10);
}

From source file:bluetoothchat.BluetoothChatFragment.java

private void updateSwapCount() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
    int count = prefs.getInt("swap count", 0);
    prefs.edit().putInt("swap count", count + 1).apply();
}

From source file:net.tac42.subtails.service.RESTMusicService.java

private HttpResponse executeWithRetry(Context context, String url, String originalUrl, HttpParams requestParams,
        List<String> parameterNames, List<Object> parameterValues, List<Header> headers,
        ProgressListener progressListener, CancellableTask task) throws IOException {
    Log.i(TAG, "Using URL " + url);

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;//from ww  w.  jav  a 2  s  . co m
        HttpContext httpContext = new BasicHttpContext();
        final HttpPost request = new HttpPost(url);

        if (task != null) {
            // Attempt to abort the HTTP request if the task is cancelled.
            task.setOnCancelListener(new CancellableTask.OnCancelListener() {
                @Override
                public void onCancel() {
                    cancelled.set(true);
                    request.abort();
                }
            });
        }

        if (parameterNames != null) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            for (int i = 0; i < parameterNames.size(); i++) {
                params.add(
                        new BasicNameValuePair(parameterNames.get(i), String.valueOf(parameterValues.get(i))));
            }
            request.setEntity(new UrlEncodedFormEntity(params, Constants.UTF_8));
        }

        if (requestParams != null) {
            request.setParams(requestParams);
            Log.d(TAG, "Socket read timeout: " + HttpConnectionParams.getSoTimeout(requestParams) + " ms.");
        }

        if (headers != null) {
            for (Header header : headers) {
                request.addHeader(header);
            }
        }

        // Set credentials to get through apache proxies that require authentication.
        SharedPreferences prefs = Util.getPreferences(context);
        int instance = prefs.getInt(Constants.PREFERENCES_KEY_SERVER_INSTANCE, 1);
        String username = prefs.getString(Constants.PREFERENCES_KEY_USERNAME + instance, null);
        String password = prefs.getString(Constants.PREFERENCES_KEY_PASSWORD + instance, null);
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(username, password));

        try {
            HttpResponse response = httpClient.execute(request, httpContext);
            detectRedirect(originalUrl, context, httpContext);
            return response;
        } catch (IOException x) {
            request.abort();
            if (attempts >= HTTP_REQUEST_MAX_ATTEMPTS || cancelled.get()) {
                throw x;
            }
            if (progressListener != null) {
                String msg = context.getResources().getString(R.string.music_service_retry, attempts,
                        HTTP_REQUEST_MAX_ATTEMPTS - 1);
                progressListener.updateProgress(msg);
            }
            Log.w(TAG, "Got IOException (" + attempts + "), will retry", x);
            increaseTimeouts(requestParams);
            Util.sleepQuietly(2000L);
        }
    }
}

From source file:uk.bowdlerize.MainActivity.java

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
    String registrationId = prefs.getString(PROPERTY_REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }/*from  w  w  w.  j  a v  a  2  s  .c o  m*/
    // Check if app was updated; if so, it must clear the registration ID
    // since the existing regID is not guaranteed to work with the new
    // app version.
    int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

From source file:com.nextgis.forestinspector.activity.MainActivity.java

protected boolean loadNotes(long resourceId, String accountName, MapBase map) {
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    long inspectorId = prefs.getInt(SettingsConstants.KEY_PREF_USERID, -1);

    NGWVectorLayerUI ngwVectorLayer = new NGWVectorLayerUI(getApplicationContext(),
            map.createLayerStorage(Constants.KEY_LAYER_NOTES));
    ngwVectorLayer.setName(getString(R.string.notes));
    ngwVectorLayer.setRemoteId(resourceId);
    ngwVectorLayer.setServerWhere(Constants.KEY_NOTES_USERID + "=" + inspectorId);
    ngwVectorLayer.setVisible(true);/* w  ww .  ja v a  2 s  .  c  om*/
    //TODO: add layer draw default style and quarter labels
    ngwVectorLayer.setAccountName(accountName);
    ngwVectorLayer.setSyncType(com.nextgis.maplib.util.Constants.SYNC_DATA);
    ngwVectorLayer.setMinZoom(0);
    ngwVectorLayer.setMaxZoom(100);

    map.addLayer(ngwVectorLayer);

    return ngwVectorLayer.download() == null;
}

From source file:com.agustinprats.myhrv.MainActivity.java

private void saveSessionDate() {
    String date = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

    SharedPreferences coherenceHistorySharedPrefs = getApplicationContext()
            .getSharedPreferences("CoherenceHistoryData1", Context.MODE_PRIVATE);
    SharedPreferences sampleSizeHistorySharedPrefs = getApplicationContext()
            .getSharedPreferences("SampleSizeHistoryData1", Context.MODE_PRIVATE);

    //    PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    int lastCoherenceAvgToday = coherenceHistorySharedPrefs.getInt(date, 0);
    int lastSampleSizeToday = sampleSizeHistorySharedPrefs.getInt(date, 0);

    if (_heartRateService != null) {
        int currentCoherenceAvg = (int) _heartRateService.getIntervals().getCoherence();
        int currentSampleSize = _heartRateService.getIntervals().size();

        if (currentSampleSize > 0) {
            int newCoherenceAvg = (lastCoherenceAvgToday * lastSampleSizeToday
                    + currentCoherenceAvg * currentSampleSize) / (lastSampleSizeToday + currentSampleSize);
            int newSampleSize = lastSampleSizeToday + currentSampleSize;

            coherenceHistorySharedPrefs.edit().putInt(date, newCoherenceAvg).commit();
            sampleSizeHistorySharedPrefs.edit().putInt(date, newSampleSize).commit();

        }/* w w  w . j av  a  2s. c  o  m*/

    }

}

From source file:com.example.devesh.Coride.DriverRegistration.java

private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getSharedPreferences(MainActivity.class.getSimpleName(),
            Context.MODE_PRIVATE);
    String registrationId = prefs.getString(REG_ID, "");
    if (registrationId.isEmpty()) {
        Log.i(TAG, "Registration not found.");
        return "";
    }// ww  w . j  av  a  2 s .  c om
    int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
        Log.i(TAG, "App version changed.");
        return "";
    }
    return registrationId;
}

From source file:com.atinternet.tracker.LifeCycle.java

static void newSessionInit(SharedPreferences preferences) {
    try {/*  ww w .  ja v  a  2 s  .  co m*/

        updateFirstSession(preferences);
        // Calcul dsfs
        String firstLaunchDate = preferences.getString(FIRST_SESSION_DATE, "");
        if (!TextUtils.isEmpty(firstLaunchDate)) {
            long timeSinceFirstLaunch = simpleDateFormat.parse(firstLaunchDate).getTime();
            preferences.edit().putInt(DAYS_SINCE_FIRST_SESSION,
                    Tool.getDaysBetweenTimes(System.currentTimeMillis(), timeSinceFirstLaunch)).apply();
        }

        // Calcul dsu
        String firstLaunchDateAfterUpdate = preferences.getString(FIRST_SESSION_DATE_AFTER_UPDATE, "");
        if (!TextUtils.isEmpty(firstLaunchDateAfterUpdate)) {
            long timeSinceFirstLaunchAfterUpdate = simpleDateFormat.parse(firstLaunchDateAfterUpdate).getTime();
            preferences.edit().putInt(DAYS_SINCE_UPDATE,
                    Tool.getDaysBetweenTimes(System.currentTimeMillis(), timeSinceFirstLaunchAfterUpdate))
                    .apply();
        }

        // Calcul dsls
        String lastLaunchDate = preferences.getString(LAST_SESSION_DATE, "");
        if (!TextUtils.isEmpty(lastLaunchDate)) {
            long timeSinceLastUse = simpleDateFormat.parse(lastLaunchDate).getTime();
            preferences.edit().putInt(DAYS_SINCE_LAST_SESSION,
                    Tool.getDaysBetweenTimes(System.currentTimeMillis(), timeSinceLastUse)).apply();
        }
        preferences.edit().putString(LAST_SESSION_DATE, simpleDateFormat.format(new Date())).apply();

        // sc
        preferences.edit().putInt(SESSION_COUNT, preferences.getInt(SESSION_COUNT, 0) + 1).apply();

        // Calcul scsu
        preferences.edit()
                .putInt(SESSION_COUNT_SINCE_UPDATE, preferences.getInt(SESSION_COUNT_SINCE_UPDATE, 0) + 1)
                .apply();

        // Application version changed
        String savedApvr = preferences.getString(VERSION_CODE_KEY, "");
        // Update detected
        if (!versionCode.equals(savedApvr)) {
            preferences.edit().putString(FIRST_SESSION_DATE_AFTER_UPDATE, simpleDateFormat.format(new Date()))
                    .putString(VERSION_CODE_KEY, versionCode).putInt(SESSION_COUNT_SINCE_UPDATE, 1)
                    .putInt(DAYS_SINCE_UPDATE, 0).putBoolean(FIRST_SESSION_AFTER_UPDATE, true).apply();
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    sessionId = UUID.randomUUID().toString();
}