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:org.getlantern.firetweet.util.Utils.java

public static HttpClientWrapper getImageLoaderHttpClient(final Context context) {
    if (context == null)
        return null;
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int timeoutMillis = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10000) * 1000;
    final Proxy proxy = getProxy(context);
    final String userAgent = generateBrowserUserAgent();
    final HostAddressResolverFactory resolverFactory = new FiretweetHostResolverFactory(
            FiretweetApplication.getInstance(context));
    return getHttpClient(context, timeoutMillis, true, proxy, resolverFactory, userAgent, false);
}

From source file:org.getlantern.firetweet.util.Utils.java

@Nullable
public static Twitter getTwitterInstance(final Context context, final long accountId,
        final boolean includeEntities, final boolean includeRetweets) {
    if (context == null)
        return null;
    final FiretweetApplication app = FiretweetApplication.getInstance(context);
    final SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    final int connection_timeout = prefs.getInt(KEY_CONNECTION_TIMEOUT, 10) * 1000;
    final boolean enableGzip = prefs.getBoolean(KEY_GZIP_COMPRESSING, true);
    final boolean ignoreSslError = prefs.getBoolean(KEY_IGNORE_SSL_ERROR, false);
    final boolean enableProxy = prefs.getBoolean(KEY_ENABLE_PROXY, false);
    // Here I use old consumer key/secret because it's default key for older
    // versions/*from  w  ww  .  j  a  va 2 s .c  o m*/
    final ParcelableCredentials credentials = ParcelableCredentials.getCredentials(context, accountId);
    if (credentials == null)
        return null;
    final ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setHostAddressResolverFactory(new FiretweetHostResolverFactory(app));
    cb.setHttpClientFactory(new OkHttpClientFactory(context));
    cb.setHttpConnectionTimeout(connection_timeout);
    cb.setGZIPEnabled(enableGzip);
    cb.setIgnoreSSLError(ignoreSslError);
    cb.setIncludeCards(true);
    cb.setCardsPlatform("Android-12");
    //            cb.setModelVersion(7);
    if (enableProxy) {
        final String proxy_host = prefs.getString(KEY_PROXY_HOST, null);
        final int proxy_port = ParseUtils.parseInt(prefs.getString(KEY_PROXY_PORT, "-1"));
        if (!isEmpty(proxy_host) && proxy_port > 0) {
            cb.setHttpProxyHost(proxy_host);
            cb.setHttpProxyPort(proxy_port);
        }
    }
    final String prefConsumerKey = prefs.getString(KEY_CONSUMER_KEY, TWITTER_CONSUMER_KEY);
    final String prefConsumerSecret = prefs.getString(KEY_CONSUMER_SECRET, TWITTER_CONSUMER_SECRET);
    final String apiUrlFormat = credentials.api_url_format;
    final String consumerKey = trim(credentials.consumer_key);
    final String consumerSecret = trim(credentials.consumer_secret);
    final boolean sameOAuthSigningUrl = credentials.same_oauth_signing_url;
    final boolean noVersionSuffix = credentials.no_version_suffix;
    if (!isEmpty(apiUrlFormat)) {
        final String versionSuffix = noVersionSuffix ? null : "/1.1/";
        cb.setRestBaseURL(getApiUrl(apiUrlFormat, "api", versionSuffix));
        cb.setOAuthBaseURL(getApiUrl(apiUrlFormat, "api", "/oauth/"));
        cb.setUploadBaseURL(getApiUrl(apiUrlFormat, "upload", versionSuffix));
        cb.setOAuthAuthorizationURL(getApiUrl(apiUrlFormat, null, null));
        if (!sameOAuthSigningUrl) {
            cb.setSigningRestBaseURL(DEFAULT_SIGNING_REST_BASE_URL);
            cb.setSigningOAuthBaseURL(DEFAULT_SIGNING_OAUTH_BASE_URL);
            cb.setSigningUploadBaseURL(DEFAULT_SIGNING_UPLOAD_BASE_URL);
        }
    }
    if (TwitterContentUtils.isOfficialKey(context, consumerKey, consumerSecret)) {
        setMockOfficialUserAgent(context, cb);
    } else {
        setUserAgent(context, cb);
    }

    cb.setIncludeEntitiesEnabled(includeEntities);
    cb.setIncludeRTsEnabled(includeRetweets);
    cb.setIncludeReplyCountEnabled(true);
    cb.setIncludeDescendentReplyCountEnabled(true);
    switch (credentials.auth_type) {
    case Accounts.AUTH_TYPE_OAUTH:
    case Accounts.AUTH_TYPE_XAUTH: {
        if (!isEmpty(consumerKey) && !isEmpty(consumerSecret)) {
            cb.setOAuthConsumerKey(consumerKey);
            cb.setOAuthConsumerSecret(consumerSecret);
        } else if (!isEmpty(prefConsumerKey) && !isEmpty(prefConsumerSecret)) {
            cb.setOAuthConsumerKey(prefConsumerKey);
            cb.setOAuthConsumerSecret(prefConsumerSecret);
        } else {
            cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
            cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
        }
        final String token = credentials.oauth_token;
        final String tokenSecret = credentials.oauth_token_secret;
        if (isEmpty(token) || isEmpty(tokenSecret))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new AccessToken(token, tokenSecret));
    }
    case Accounts.AUTH_TYPE_BASIC: {
        final String screenName = credentials.screen_name;
        final String username = credentials.basic_auth_username;
        final String loginName = username != null ? username : screenName;
        final String password = credentials.basic_auth_password;
        if (isEmpty(loginName) || isEmpty(password))
            return null;
        return new TwitterFactory(cb.build()).getInstance(new BasicAuthorization(loginName, password));
    }
    case Accounts.AUTH_TYPE_TWIP_O_MODE: {
        return new TwitterFactory(cb.build()).getInstance(new TwipOModeAuthorization());
    }
    default: {
        return null;
    }
    }
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

private int getLastUsedListFromPrefs() {

    SharedPreferences sp = getSharedPreferences("org.openintents.shopping_preferences", MODE_PRIVATE);

    return sp.getInt(PreferenceActivity.PREFS_LASTUSED, 1);
}

From source file:mp.teardrop.PlaybackService.java

private void loadPreference(String key) {
    SharedPreferences settings = getSettings(this);
    if (PrefKeys.HEADSET_PAUSE.equals(key)) {
        mHeadsetPause = settings.getBoolean(PrefKeys.HEADSET_PAUSE, true);
    } else if (PrefKeys.NOTIFICATION_ACTION.equals(key)) {
        mNotificationAction = createNotificationAction(settings);
        updateNotification();/*w  w w .j  a va 2s  .  c  o m*/
    } else if (PrefKeys.NOTIFICATION_INVERTED_COLOR.equals(key)) {
        mInvertNotification = settings.getBoolean(PrefKeys.NOTIFICATION_INVERTED_COLOR, false);
        updateNotification();
    } else if (PrefKeys.NOTIFICATION_MODE.equals(key)) {
        mNotificationMode = Integer.parseInt(settings.getString(PrefKeys.NOTIFICATION_MODE, "1"));
        // This is the only way to remove a notification created by
        // startForeground(), even if we are not currently in foreground
        // mode.
        stopForeground(true);
        updateNotification();
    } else if (PrefKeys.SCROBBLE.equals(key)) {
        mScrobble = settings.getBoolean(PrefKeys.SCROBBLE, false);
    } else if (PrefKeys.MEDIA_BUTTON.equals(key) || PrefKeys.MEDIA_BUTTON_BEEP.equals(key)) {
        MediaButtonReceiver.reloadPreference(this);
    } else if (PrefKeys.USE_IDLE_TIMEOUT.equals(key) || PrefKeys.IDLE_TIMEOUT.equals(key)) {
        mIdleTimeout = settings.getBoolean(PrefKeys.USE_IDLE_TIMEOUT, false)
                ? settings.getInt(PrefKeys.IDLE_TIMEOUT, 3600)
                : 0;
        userActionTriggered();
    } else if (PrefKeys.COVERLOADER_ANDROID.equals(key)) {
        Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_ANDROID, true)
                ? Song.mCoverLoadMode | Song.COVER_MODE_ANDROID
                : Song.mCoverLoadMode & ~(Song.COVER_MODE_ANDROID);
        Song.mFlushCoverCache = true;
    } else if (PrefKeys.COVERLOADER_VANILLA.equals(key)) {
        Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_VANILLA, true)
                ? Song.mCoverLoadMode | Song.COVER_MODE_VANILLA
                : Song.mCoverLoadMode & ~(Song.COVER_MODE_VANILLA);
        Song.mFlushCoverCache = true;
    } else if (PrefKeys.COVERLOADER_SHADOW.equals(key)) {
        Song.mCoverLoadMode = settings.getBoolean(PrefKeys.COVERLOADER_SHADOW, true)
                ? Song.mCoverLoadMode | Song.COVER_MODE_SHADOW
                : Song.mCoverLoadMode & ~(Song.COVER_MODE_SHADOW);
        Song.mFlushCoverCache = true;
    } else if (PrefKeys.NOTIFICATION_INVERTED_COLOR.equals(key)) {
        updateNotification();
    } else if (PrefKeys.HEADSET_ONLY.equals(key)) {
        mHeadsetOnly = settings.getBoolean(key, false);
        if (mHeadsetOnly && isSpeakerOn())
            unsetFlag(FLAG_PLAYING);
    } else if (PrefKeys.STOCK_BROADCAST.equals(key)) {
        mStockBroadcast = settings.getBoolean(key, false);
    } else if (PrefKeys.ENABLE_SHAKE.equals(key) || PrefKeys.SHAKE_ACTION.equals(key)) {
        mShakeAction = settings.getBoolean(PrefKeys.ENABLE_SHAKE, false)
                ? Action.getAction(settings, PrefKeys.SHAKE_ACTION, Action.NextSong)
                : Action.Nothing;
        setupSensor();
    } else if (PrefKeys.SHAKE_THRESHOLD.equals(key)) {
        mShakeThreshold = settings.getInt(PrefKeys.SHAKE_THRESHOLD, 80) / 10.0f;
    } else if (PrefKeys.ENABLE_TRACK_REPLAYGAIN.equals(key)) {
        mReplayGainTrackEnabled = settings.getBoolean(PrefKeys.ENABLE_TRACK_REPLAYGAIN, false);
        refreshReplayGainValues();
    } else if (PrefKeys.ENABLE_ALBUM_REPLAYGAIN.equals(key)) {
        mReplayGainAlbumEnabled = settings.getBoolean(PrefKeys.ENABLE_ALBUM_REPLAYGAIN, false);
        refreshReplayGainValues();
    } else if (PrefKeys.REPLAYGAIN_BUMP.equals(key)) {
        mReplayGainBump = settings.getInt(PrefKeys.REPLAYGAIN_BUMP, 75);
        refreshReplayGainValues();
    } else if (PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP.equals(key)) {
        mReplayGainUntaggedDeBump = settings.getInt(PrefKeys.REPLAYGAIN_UNTAGGED_DEBUMP, 150);
        refreshReplayGainValues();
    } else if (PrefKeys.ENABLE_READAHEAD.equals(key)) {
        mReadaheadEnabled = settings.getBoolean(PrefKeys.ENABLE_READAHEAD, false);
    }
    /* Tell androids cloud-backup manager that we just changed our preferences */
    (new BackupManager(this)).dataChanged();
}

From source file:github.daneren2005.dsub.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 {
    // Strip out sensitive information from log
    Log.i(TAG, "Using URL " + url.substring(0, url.indexOf("?u=") + 1) + url.substring(url.indexOf("&v=") + 1));

    SharedPreferences prefs = Util.getPreferences(context);
    int networkTimeout = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT, "15000"));
    HttpParams newParams = httpClient.getParams();
    HttpConnectionParams.setSoTimeout(newParams, networkTimeout);
    httpClient.setParams(newParams);//from   ww  w  .  j  av a2s .  c  o  m

    final AtomicReference<Boolean> cancelled = new AtomicReference<Boolean>(false);
    int attempts = 0;
    while (true) {
        attempts++;
        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() {
                    new Thread(new Runnable() {
                        public void run() {
                            try {
                                cancelled.set(true);
                                request.abort();
                            } catch (Exception e) {
                                Log.e(TAG, "Failed to stop http task");
                            }
                        }
                    }).start();
                }
            });
        }

        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.
        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:com.updetector.MainActivity.java

/**
* Handle Performance Tuning Click/* w ww .  j av  a2s. c  o m*/
*/
private void handleAdvancedSetting() {
    final Dialog dialog = new Dialog(this);
    dialog.setTitle(R.string.menu_item_advanced_settings);
    dialog.setContentView(R.layout.advanced_setting);

    final SharedPreferences mPrefs = getSharedPreferences(Constants.SHARED_PREFERENCES, Context.MODE_PRIVATE);
    final Editor editor = mPrefs.edit();

    final ToggleButton classifierForCIVOnButton = (ToggleButton) dialog.findViewById(R.id.civ_classifier_on);
    classifierForCIVOnButton.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, false));

    final ToggleButton isOutdoorButton = (ToggleButton) dialog.findViewById(R.id.is_outdoor);
    isOutdoorButton.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, false));

    final EditText notificationTresholdText = (EditText) dialog.findViewById(R.id.notification_threshold);
    notificationTresholdText
            .setText(String.format("%.2f", mPrefs.getFloat(Constants.PREFERENCE_KEY_NOTIFICATION_THRESHOLD,
                    (float) Constants.DEFAULT_DETECTION_THRESHOLD)));

    //final EditText detectionIntervalText=(EditText)dialog.findViewById(R.id.detection_interval);
    //detectionIntervalText.setText(String.valueOf(mPrefs.getInt(Constants.PREFERENCE_KEY_DETECTION_INTERVAL, Constants.DETECTION_INTERVAL_DEFAULT_VALUE) ));

    final EditText googleActivityUpdateIntervalText = (EditText) dialog
            .findViewById(R.id.google_activity_update_interval);
    googleActivityUpdateIntervalText
            .setText(String.valueOf(mPrefs.getInt(Constants.PREFERENCE_KEY_GOOGLE_ACTIVITY_UPDATE_INTERVAL,
                    Constants.GOOGLE_ACTIVITY_UPDATE_INTERVAL_DEFAULT_VALUE)));

    //final ToggleButton useGoogleActivityInFusion=(ToggleButton)dialog.findViewById(R.id.use_google_for_motion_state_in_fusion);
    //useGoogleActivityInFusion.setChecked(mPrefs.getBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, false));

    final ToggleButton logAcclRawButton = (ToggleButton) dialog.findViewById(R.id.log_raw_switch);
    logAcclRawButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, false));

    final ToggleButton logGoogleActUpdatesButton = (ToggleButton) dialog
            .findViewById(R.id.log_google_updates_switch);
    logGoogleActUpdatesButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, false));

    final ToggleButton logDetectionButton = (ToggleButton) dialog.findViewById(R.id.log_report_switch);
    logDetectionButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_DETECTION_SWITCH, false));

    final ToggleButton logErrorButton = (ToggleButton) dialog.findViewById(R.id.log_error_switch);
    logErrorButton.setChecked(mPrefs.getBoolean(Constants.LOGGING_ERROR_SWITCH, true));

    //final EditText deltaForConditionalProb=(EditText)dialog.findViewById(R.id.normal_dist_delta);
    //deltaForConditionalProb.setText(String.valueOf(mPrefs.getFloat(Constants.CIV_DELTA_CONDITIONAL_PROBABILITY, 2)) );      

    final Button applyButton = (Button) dialog.findViewById(R.id.performance_apply_button);
    final Button cancelButton = (Button) dialog.findViewById(R.id.peformance_cancel_button);
    applyButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            if (classifierForCIVOnButton.isChecked())
                editor.putBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, true);
            else
                editor.putBoolean(Constants.PREFERENCE_KEY_CIV_CLASSIFIER_ON, false);

            if (isOutdoorButton.isChecked())
                editor.putBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, true);
            else
                editor.putBoolean(Constants.PREFERENCE_KEY_IS_OUTDOOR, false);

            if (logAcclRawButton.isChecked())
                editor.putBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_ACCL_RAW_SWITCH, false);

            if (logGoogleActUpdatesButton.isChecked())
                editor.putBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, true);
            else
                editor.putBoolean(Constants.LOGGING_GOOGLE_ACTIVITY_UPDATE, false);

            if (logDetectionButton.isChecked())
                editor.putBoolean(Constants.LOGGING_DETECTION_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_DETECTION_SWITCH, false);

            if (logErrorButton.isChecked())
                editor.putBoolean(Constants.LOGGING_ERROR_SWITCH, true);
            else
                editor.putBoolean(Constants.LOGGING_ERROR_SWITCH, false);

            float notificationTreshold;
            try {
                notificationTreshold = Float.parseFloat(notificationTresholdText.getText().toString());
            } catch (Exception ex) {
                notificationTreshold = (float) Constants.DEFAULT_DETECTION_THRESHOLD;
            }
            editor.putFloat(Constants.PREFERENCE_KEY_NOTIFICATION_THRESHOLD, notificationTreshold);

            /*int detectionInterval;
            try{
               detectionInterval=Integer.parseInt(
             detectionIntervalText.getText().toString());
            }catch(Exception ex){
               detectionInterval=Constants.DETECTION_INTERVAL_DEFAULT_VALUE;
            }
            editor.putInt(Constants.PREFERENCE_KEY_DETECTION_INTERVAL, detectionInterval);*/

            /*if (useGoogleActivityInFusion.isChecked())
               editor.putBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, true);
            else
               editor.putBoolean(Constants.PREFERENCE_KEY_USE_GOOGLE_ACTIVITY_IN_FUSION, false);*/

            int googleActivityUpdateInterval;
            try {
                googleActivityUpdateInterval = Integer
                        .parseInt(googleActivityUpdateIntervalText.getText().toString());
            } catch (Exception ex) {
                googleActivityUpdateInterval = Constants.GOOGLE_ACTIVITY_UPDATE_INTERVAL_DEFAULT_VALUE;
            }
            editor.putInt(Constants.PREFERENCE_KEY_GOOGLE_ACTIVITY_UPDATE_INTERVAL,
                    googleActivityUpdateInterval);

            /*try{
               Float delta=Float.parseFloat(deltaForConditionalProb.getText().toString());
               editor.putFloat(Constants.CIV_DELTA_CONDITIONAL_PROBABILITY, delta);
            }catch(Exception ex){
               Toast.makeText(getApplicationContext(), "Input must be a float number", Toast.LENGTH_SHORT).show();
            }*/

            editor.commit();
            dialog.cancel();
        }
    });

    cancelButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(final View v) {
            dialog.cancel();
        }
    });
    dialog.show();
}

From source file:com.piusvelte.taplock.client.core.TapLockSettings.java

@Override
protected void onResume() {
    super.onResume();
    Intent intent = getIntent();/*from   w  w w  . j  a  v  a  2  s  .c  om*/
    if (mInWriteMode) {
        if (intent != null) {
            String action = intent.getAction();
            if (mInWriteMode && NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
                    && intent.hasExtra(EXTRA_DEVICE_NAME)) {
                Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
                String name = intent.getStringExtra(EXTRA_DEVICE_NAME);
                if ((tag != null) && (name != null)) {
                    // write the device and address
                    String lang = "en";
                    // don't write the passphrase!
                    byte[] textBytes = name.getBytes();
                    byte[] langBytes = null;
                    int langLength = 0;
                    try {
                        langBytes = lang.getBytes("US-ASCII");
                        langLength = langBytes.length;
                    } catch (UnsupportedEncodingException e) {
                        Log.e(TAG, e.toString());
                    }
                    int textLength = textBytes.length;
                    byte[] payload = new byte[1 + langLength + textLength];

                    // set status byte (see NDEF spec for actual bits)
                    payload[0] = (byte) langLength;

                    // copy langbytes and textbytes into payload
                    if (langBytes != null) {
                        System.arraycopy(langBytes, 0, payload, 1, langLength);
                    }
                    System.arraycopy(textBytes, 0, payload, 1 + langLength, textLength);
                    NdefRecord record = new NdefRecord(NdefRecord.TNF_WELL_KNOWN, NdefRecord.RTD_TEXT,
                            new byte[0], payload);
                    NdefMessage message = new NdefMessage(
                            new NdefRecord[] { record, NdefRecord.createApplicationRecord(getPackageName()) });
                    // Get an instance of Ndef for the tag.
                    Ndef ndef = Ndef.get(tag);
                    if (ndef != null) {
                        try {
                            ndef.connect();
                            if (ndef.isWritable()) {
                                ndef.writeNdefMessage(message);
                            }
                            ndef.close();
                            Toast.makeText(this, "tag written", Toast.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.e(TAG, e.toString());
                        } catch (FormatException e) {
                            Log.e(TAG, e.toString());
                        }
                    } else {
                        NdefFormatable format = NdefFormatable.get(tag);
                        if (format != null) {
                            try {
                                format.connect();
                                format.format(message);
                                format.close();
                                Toast.makeText(getApplicationContext(), "tag written", Toast.LENGTH_LONG);
                            } catch (IOException e) {
                                Log.e(TAG, e.toString());
                            } catch (FormatException e) {
                                Log.e(TAG, e.toString());
                            }
                        }
                    }
                    mNfcAdapter.disableForegroundDispatch(this);
                }
            }
        }
        mInWriteMode = false;
    } else {
        SharedPreferences sp = getSharedPreferences(KEY_PREFS, MODE_PRIVATE);
        onSharedPreferenceChanged(sp, KEY_DEVICES);
        // check if configuring a widget
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                final String[] displayNames = TapLock.getDeviceNames(mDevices);
                final int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID,
                        AppWidgetManager.INVALID_APPWIDGET_ID);
                if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
                    mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle("Select device for widget")
                            .setItems(displayNames, new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    // set the successful widget result
                                    Intent resultValue = new Intent();
                                    resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
                                    setResult(RESULT_OK, resultValue);

                                    // broadcast the new widget to update
                                    JSONObject deviceJObj = mDevices.get(which);
                                    dialog.cancel();
                                    TapLockSettings.this.finish();
                                    try {
                                        sendBroadcast(TapLock
                                                .getPackageIntent(TapLockSettings.this, TapLockWidget.class)
                                                .setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE)
                                                .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId)
                                                .putExtra(EXTRA_DEVICE_NAME, deviceJObj.getString(KEY_NAME)));
                                    } catch (JSONException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                }
                            }).create();
                    mDialog.show();
                }
            }
        }
        // start the service before binding so that the service stays around for faster future connections
        startService(TapLock.getPackageIntent(this, TapLockService.class));
        bindService(TapLock.getPackageIntent(this, TapLockService.class), this, BIND_AUTO_CREATE);

        int serverVersion = sp.getInt(KEY_SERVER_VERSION, 0);
        if (mShowTapLockSettingsInfo && (mDevices.size() == 0)) {
            if (serverVersion < SERVER_VERSION)
                sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mShowTapLockSettingsInfo = false;
            Intent i = TapLock.getPackageIntent(this, TapLockInfo.class);
            i.putExtra(EXTRA_INFO, getString(R.string.info_taplocksettings));
            startActivity(i);
        } else if (serverVersion < SERVER_VERSION) {
            // TapLockServer has been updated
            sp.edit().putInt(KEY_SERVER_VERSION, SERVER_VERSION).commit();
            mDialog = new AlertDialog.Builder(TapLockSettings.this).setTitle(R.string.ttl_hasupdate)
                    .setMessage(R.string.msg_hasupdate)
                    .setNeutralButton(R.string.button_getserver, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();

                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                    .setTitle(R.string.msg_pickinstaller)
                                    .setItems(R.array.installer_entries, new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            dialog.cancel();
                                            final String installer_file = getResources()
                                                    .getStringArray(R.array.installer_values)[which];

                                            mDialog = new AlertDialog.Builder(TapLockSettings.this)
                                                    .setTitle(R.string.msg_pickdownloader)
                                                    .setItems(R.array.download_entries,
                                                            new DialogInterface.OnClickListener() {

                                                                @Override
                                                                public void onClick(DialogInterface dialog,
                                                                        int which) {
                                                                    dialog.cancel();
                                                                    String action = getResources()
                                                                            .getStringArray(
                                                                                    R.array.download_values)[which];
                                                                    if (ACTION_DOWNLOAD_SDCARD.equals(action)
                                                                            && copyFileToSDCard(installer_file))
                                                                        Toast.makeText(TapLockSettings.this,
                                                                                "Done!", Toast.LENGTH_SHORT)
                                                                                .show();
                                                                    else if (ACTION_DOWNLOAD_EMAIL
                                                                            .equals(action)
                                                                            && copyFileToSDCard(
                                                                                    installer_file)) {
                                                                        Intent emailIntent = new Intent(
                                                                                android.content.Intent.ACTION_SEND);
                                                                        emailIntent.setType(
                                                                                "application/java-archive");
                                                                        emailIntent.putExtra(Intent.EXTRA_TEXT,
                                                                                getString(
                                                                                        R.string.email_instructions));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_SUBJECT,
                                                                                getString(R.string.app_name));
                                                                        emailIntent.putExtra(
                                                                                Intent.EXTRA_STREAM,
                                                                                Uri.parse("file://"
                                                                                        + Environment
                                                                                                .getExternalStorageDirectory()
                                                                                                .getPath()
                                                                                        + "/"
                                                                                        + installer_file));
                                                                        startActivity(Intent.createChooser(
                                                                                emailIntent, getString(
                                                                                        R.string.button_getserver)));
                                                                    }
                                                                }

                                                            })
                                                    .create();
                                            mDialog.show();
                                        }
                                    }).create();
                            mDialog.show();
                        }
                    }).create();
            mDialog.show();
        }
    }
}

From source file:org.getlantern.firetweet.util.Utils.java

public static void configBaseAdapter(final Context context, final IBaseAdapter adapter) {
    if (context == null)
        return;/*from  w  w w  .j  a  v a 2 s.  co  m*/
    final SharedPreferences pref = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    adapter.setDisplayProfileImage(pref.getBoolean(KEY_DISPLAY_PROFILE_IMAGE, true));
    adapter.setDisplayNameFirst(pref.getBoolean(KEY_NAME_FIRST, true));
    adapter.setLinkHighlightOption(pref.getString(KEY_LINK_HIGHLIGHT_OPTION, VALUE_LINK_HIGHLIGHT_OPTION_NONE));
    adapter.setTextSize(pref.getInt(KEY_TEXT_SIZE, getDefaultTextSize(context)));
    adapter.notifyDataSetChanged();
}

From source file:com.xplink.android.carchecklist.CarCheckListActivity.java

private int getCheckedNumFromShared(String key) {
    SharedPreferences shared = getSharedPreferences("mysettings", Context.MODE_PRIVATE);
    return shared.getInt(key, 0);
}

From source file:com.xplink.android.carchecklist.CarCheckListActivity.java

public void CheckRatio() {
    // Log.i("checknum", "in checknum : " + Checknum);
    SharedPreferences shared = getSharedPreferences("mysettings", Context.MODE_PRIVATE);
    Checknum = shared.getInt("checknum", 0);
    PercenRatio = shared.getInt("percenRatio", PercenRatio);

    PercenPower = shared.getInt("PercenPower", PercenPower);
    PercenEngine = shared.getInt("PercenEngine", PercenEngine);
    PercenExterior = shared.getInt("PercenExterior", PercenExterior);
    PercenInterior = shared.getInt("PercenInterior", PercenInterior);
    PercenDocument = shared.getInt("PercenDocument", PercenDocument);

    CheckExteriorTotal = shared.getInt("CheckExteriorTotal", 0);
    CheckInteriorTotal = shared.getInt("CheckInteriorTotal", 0);
    CheckPowerTotal = shared.getInt("CheckPowerTotal", 0);
    CheckEngineTotal = shared.getInt("CheckEngineTotal", 0);
    CheckDocumentTotal = shared.getInt("CheckDocumentTotal", 0);

    Checknum = shared.getInt("checknum", 0);

    // check value
    Log.i("checklist", "PercenPower : " + PercenPower);
    Log.i("checklist", "PercenEngine : " + PercenEngine);
    Log.i("checklist", "PercenExterior : " + PercenExterior);
    Log.i("checklist", "PercenInterior : " + PercenInterior);
    Log.i("checklist", "PercenDocument : " + PercenDocument);
    Log.i("checklist", "PercenRatio : " + PercenRatio);
    Log.i("checklist", "Checknum : " + Checknum);
    // check value

    PowerProgress.setProgress(PercenPower);
    EngineProgress.setProgress(PercenEngine);
    ExteriorProgress.setProgress(PercenExterior);
    InteriorProgress.setProgress(PercenInterior);
    DocumentProgress.setProgress(PercenDocument);

    percenpower.setText("" + PercenPower + "%");
    percenengine.setText("" + PercenEngine + "%");
    percenexterior.setText("" + PercenExterior + "%");
    perceninterior.setText("" + PercenInterior + "%");
    percendocument.setText("" + PercenDocument + "%");

    // Log.i("Checknum", "Checknum in CHECKRATIO : " + Checknum);
    // Log.i("PercenRatio", "PercenRatio >>>> " + PercenRatio);
    if (Checknum > 0) {
        Ratiotext.setText("Rating of the Vehicle.   " + PercenRatio + "  %");
        RatioProgress.setProgress(PercenRatio);
        Ratiotext.setVisibility(TextView.VISIBLE);
        RatioProgress.setVisibility(ProgressBar.VISIBLE);
    } else {//from  w ww.  j a  v a 2  s  . c  o  m
        Ratiotext.setVisibility(TextView.INVISIBLE);
        RatioProgress.setVisibility(ProgressBar.INVISIBLE);
    }

}