Example usage for android.content SharedPreferences contains

List of usage examples for android.content SharedPreferences contains

Introduction

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

Prototype

boolean contains(String key);

Source Link

Document

Checks whether the preferences contains a preference.

Usage

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoDeviceHelper.java

/**
 * Returns the cached key for this device. Device keys are stored in SharedPreferences and are
 * used to track devices. Returns null if no device key was cached.
 *
 * @param username          REQUIRED: The current user.
 * @param userPoolId        REQUIRED: Client ID of the application.
 * @param context           REQUIRED: Application context.
 * @return device key as String, null if the device-key is not available.
 *///from   w w w.  j  a v  a 2 s  .  c om
public static String getDeviceKey(String username, String userPoolId, Context context) {
    try {
        final SharedPreferences cipCachedDeviceDetails = context
                .getSharedPreferences(getDeviceDetailsCacheForUser(username, userPoolId), 0);
        if (cipCachedDeviceDetails != null && cipCachedDeviceDetails.contains(COGNITO_DEVICE_KEY)) {
            return cipCachedDeviceDetails.getString(COGNITO_DEVICE_KEY, null);
        }
    } catch (final Exception e) {
        LOGGER.error("Error accessing SharedPreferences", e);
    }
    return null;
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoDeviceHelper.java

/**
 * Returns the cached device secret for this device. Device secret is generated when the device
 * is confirmed and is used for device identification.
 *
 * @param username          REQUIRED: The current user.
 * @param userPoolId        REQUIRED: Client ID of the application.
 * @param context           REQUIRED: Application context.
 * @return device secret as String, null if the device-key is not available.
 *//* w  w  w  .  jav a 2 s .  c o  m*/
public static String getDeviceSecret(String username, String userPoolId, Context context) {
    try {
        final SharedPreferences cipCachedDeviceDetails = context
                .getSharedPreferences(getDeviceDetailsCacheForUser(username, userPoolId), 0);
        if (cipCachedDeviceDetails != null && cipCachedDeviceDetails.contains(COGNITO_DEVICE_SECRET)) {
            return cipCachedDeviceDetails.getString(COGNITO_DEVICE_SECRET, null);
        }
    } catch (final Exception e) {
        LOGGER.error("Error accessing SharedPreferences", e);
    }
    return null;
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.util.CognitoDeviceHelper.java

/**
 * Returns the cached device group key for this device. Device secret is generated when the device
 * is confirmed and is used for device identification.
 *
 * @param username          REQUIRED: The current user.
 * @param userPoolId        REQUIRED: Client ID of the application.
 * @param context           REQUIRED: Application context.
 * @return device group key as String, null if the device-key is not available.
 *///from   w  ww . ja v a2  s.  c  o  m
public static String getDeviceGroupKey(String username, String userPoolId, Context context) {
    try {
        final SharedPreferences cipCachedDeviceDetails = context
                .getSharedPreferences(getDeviceDetailsCacheForUser(username, userPoolId), 0);
        if (cipCachedDeviceDetails != null && cipCachedDeviceDetails.contains(COGNITO_DEVICE_GROUP_KEY)) {
            return cipCachedDeviceDetails.getString(COGNITO_DEVICE_GROUP_KEY, null);
        }
    } catch (final Exception e) {
        LOGGER.error("Error accessing SharedPreferences", e);
    }
    return null;
}

From source file:edu.rowan.app.fragments.FoodRatingFragment.java

/**
 * Start pre-fetching data (load data before it is needed)
 * /*from   w w w.j  ava2s. co m*/
 * @param reference Activity reference required for AQuery
 */
public static void prefetch(Activity reference, boolean updateCache, FoodRatingFragment callback) {
    SharedPreferences prefs = reference.getSharedPreferences(FoodRatingFragment.PREFS, 0);
    if (!prefs.contains(FoodRatingFragment.USER_ID)) { // we need to get a userId
        getUserID(reference);
    }
    long lastUpdate = prefs.getLong(LAST_REFRESH, 0);
    // [difference] / (milis * seconds * minutes)
    int hourDifference = (int) (Calendar.getInstance().getTimeInMillis() - lastUpdate) / (1000 * 60 * 60);
    Log.d("FoodRatingFragment", "Hour difference: " + hourDifference);
    if (updateCache || hourDifference > UPDATE_INTERVAL || lastUpdate == 0) {
        Log.d("FoodRatingFragment", "Fetching Ratings");
        fetchAllRatings(reference, callback);
    } else {
        Log.d("FoodRatingFragment", "Cached food ratings");
        Log.d("Marketplace",
                prefs.getString(Integer.toString(prefs.getInt(TYPE_MARKETPLACE, 0)), "CACHE FAIL"));
        Log.d("Smokehouse", prefs.getString(Integer.toString(prefs.getInt(TYPE_SMOKEHOUSE, 0)), "CACHE FAIL"));

    }
}

From source file:com.aegiswallet.utils.WalletUtils.java

public static void writeEncryptedKeys(@Nonnull final Writer out, @Nonnull final List<ECKey> keys,
        SharedPreferences prefs, String passOrNFC) throws IOException {

    boolean nfcEnabled = prefs.contains(Constants.SHAMIR_ENCRYPTED_KEY) ? false : true;

    String x1 = prefs.getString(Constants.SHAMIR_LOCAL_KEY, null);
    String x2 = null;/*from   w  w w.  ja  va 2  s. c o  m*/
    String encodedEncryptedX2 = null;

    if (!nfcEnabled) {
        x2 = prefs.getString(Constants.SHAMIR_ENCRYPTED_KEY, null);
        String encryptedX2 = encryptString(x2, passOrNFC);
        encodedEncryptedX2 = Base64.encodeToString(encryptedX2.getBytes("UTF-8"), Base64.NO_WRAP);
    }

    out.write("# PRIVATE KEYS ARE ENCRYPTED WITH SHAMIR SECRET SHARING\n");
    out.write("# TO DECRYPT - Import this backup and provide your password or NFC token\n");
    out.write("# If password/NFC token are lost, contact Bitcoin Security Project. We may be able to help.\n");
    out.write("#" + x1);
    out.write("\n");

    if (!nfcEnabled && encodedEncryptedX2 != null) {
        out.write("#X2:" + encodedEncryptedX2);
        out.write("\n");
        out.write("#ENCTYPE:PASSWORD");
    }
    //Means NFC is enabled and we're using that for encryption
    else if (nfcEnabled) {
        out.write("#ENCTYPE:NFC");
    }

    out.write("\n");

    BigInteger mainKey = null;
    if (nfcEnabled) {
        mainKey = generateSecretFromStrings(x1, passOrNFC, null);
    } else if (x2 != null) {
        mainKey = generateSecretFromStrings(x1, x2, null);
    }

    String mainKeyHash = convertToSha256(mainKey.toString());

    for (final ECKey key : keys) {
        String encodedKey = key.getPrivateKeyEncoded(Constants.NETWORK_PARAMETERS).toString();
        String encryptedKey = encryptString(encodedKey, mainKeyHash);

        out.write(Base64.encodeToString(encryptedKey.getBytes(), Base64.NO_WRAP));
        out.write('\n');
    }
}

From source file:org.andstatus.app.util.MyLog.java

public static void logSharedPreferencesValue(Object objTag, SharedPreferences sharedPreferences, String key) {
    if (!isLoggable(objTag, DEBUG)) {
        return;/*from   w w w .j  a  v a 2  s .c o m*/
    }
    String value = "(not set)";
    if (sharedPreferences.contains(key)) {
        try {
            value = sharedPreferences.getString(key, "");
        } catch (ClassCastException e1) {
            MyLog.ignored(objTag, e1);
            try {
                value = Boolean.toString(sharedPreferences.getBoolean(key, false));
            } catch (ClassCastException e2) {
                MyLog.ignored(objTag, e2);
                value = "??";
            }
        }
    }
    d(objTag, "SharedPreference: " + key + "='" + value + "'");
}

From source file:com.google.android.apps.muzei.notifications.NewWallpaperNotificationReceiver.java

/**
 * Create the notification channel for the New Wallpaper notification
 * @return False only in the case where the user had wallpapers disabled in-app, but has not
 * yet seen the 'Review your notification settings' notification
 *///  w  w w .j  av  a  2  s  .c o m
@RequiresApi(api = Build.VERSION_CODES.O)
static boolean createNotificationChannel(Context context) {
    NotificationManager notificationManager = context.getSystemService(NotificationManager.class);
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    // On O+ devices, we want to push users to change the system notification setting
    // but we'll use their current value to set the default importance
    int defaultImportance = sp.getBoolean(PREF_ENABLED, true) ? NotificationManager.IMPORTANCE_MIN
            : NotificationManager.IMPORTANCE_NONE;
    if (sp.contains(PREF_ENABLED)) {
        sp.edit().remove(PREF_ENABLED).apply();
        if (defaultImportance == NotificationManager.IMPORTANCE_NONE) {
            // Check to see if there was already a channel and give users an
            // easy way to review their notification settings if they had
            // previously disabled notifications but have not yet disabled
            // the channel
            NotificationChannel existingChannel = notificationManager
                    .getNotificationChannel(NOTIFICATION_CHANNEL);
            if (existingChannel != null
                    && existingChannel.getImportance() != NotificationManager.IMPORTANCE_NONE) {
                // Construct an Intent to get to the notification settings screen
                Intent settingsIntent = new Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS);
                settingsIntent.putExtra(Settings.EXTRA_APP_PACKAGE, context.getPackageName());
                settingsIntent.putExtra(Settings.EXTRA_CHANNEL_ID,
                        NewWallpaperNotificationReceiver.NOTIFICATION_CHANNEL);
                // Build the notification
                NotificationCompat.Builder builder = new NotificationCompat.Builder(context,
                        NOTIFICATION_CHANNEL).setSmallIcon(R.drawable.ic_stat_muzei)
                                .setColor(ContextCompat.getColor(context, R.color.notification))
                                .setAutoCancel(true)
                                .setContentTitle(context.getText(R.string.notification_settings_moved_title))
                                .setContentText(context.getText(R.string.notification_settings_moved_text))
                                .setContentIntent(PendingIntent.getActivity(context, 0, settingsIntent,
                                        PendingIntent.FLAG_UPDATE_CURRENT))
                                .setStyle(new NotificationCompat.BigTextStyle()
                                        .bigText(context.getText(R.string.notification_settings_moved_text)));
                notificationManager.notify(1, builder.build());
                return false;
            }
        }
    }
    NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL,
            context.getString(R.string.notification_new_wallpaper_channel_name), defaultImportance);
    channel.setShowBadge(false);
    notificationManager.createNotificationChannel(channel);
    return true;
}

From source file:se.bitcraze.crazyfliecontrol.prefs.PreferencesActivity.java

/**
 * Set default joystick size according to screen size
 *
 * @param context/* ww  w  .java2 s . c  om*/
 */
public static void setDefaultJoystickSize(Context context) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);

    // If no default value exists, set new default value according to screen size
    if (!sharedPreferences.contains(KEY_PREF_JOYSTICK_SIZE)) {
        String defaultValue = getDefaultJoystickSize(context);
        Log.d(LOG_TAG, "Prefs do NOT contain joystick size. Setting new default: " + defaultValue);

        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(PreferencesActivity.KEY_PREF_JOYSTICK_SIZE, String.valueOf(defaultValue));
        editor.apply();
    } else {
        Log.d(LOG_TAG, "Prefs already contain joystick size.");
    }
}

From source file:net.mceoin.cominghome.NestUtils.java

public static void getInfo(final Context context, String access_token) {
    if (debug)//from   w  w w . j av  a2s .c om
        Log.d(TAG, "getInfo()");
    if (context == null) {
        Log.e(TAG, "missing context");
        return;
    }

    // Tag used to cancel the request
    String tag_update_status = "nest_info_req";

    String url = "https://developer-api.nest.com/structures?auth=" + access_token;

    JsonObjectRequest updateStatusReq = new JsonObjectRequest(Request.Method.GET, url, null,
            new Response.Listener<JSONObject>() {

                @Override
                public void onResponse(JSONObject response) {
                    if (debug)
                        Log.d(TAG, "response=" + response.toString());

                    // {
                    // "structure_id":"njBTS-gAhF1mJ8_oF23ne7JNDyx1m1hULWixOD6IQWEe-SFA",
                    // "thermostats":["n232323jy8Xr1HVc2OGqICVP45i-Mc"],
                    // "smoke_co_alarms":["pt00ag34grggZchI7ICVPddi-Mc"],
                    // "country_code":"US",
                    // "away":"home"
                    // "name":"Home"
                    // }

                    String structure_id = "";
                    String structure_name = "";
                    String away_status = "";

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(AppController.getInstance().getApplicationContext());
                    boolean structure_id_selected = prefs.contains(MainActivity.PREFS_STRUCTURE_ID);
                    String structure_id_current = prefs.getString(MainActivity.PREFS_STRUCTURE_ID, "");
                    boolean current_in_structures = false;
                    String last_structure_name = "";
                    String last_away_status = "";
                    HashSet<String> structure_ids = new HashSet<>();

                    // use this for faking additional structures
                    if (debug) {
                        StructuresUpdate.update(context, "demo_id", "Demo Structure", "home");
                        structure_ids.add("demo_id");
                    }

                    JSONObject structures;
                    try {
                        structures = new JSONObject(response.toString());
                        Iterator<String> keys = structures.keys();
                        while (keys.hasNext()) {
                            String structure = keys.next();
                            JSONObject value = structures.getJSONObject(structure);
                            if (debug)
                                Log.d(TAG, "value=" + value);
                            structure_id = value.getString("structure_id");
                            structure_name = value.getString("name");
                            away_status = value.getString("away");

                            StructuresUpdate.update(context, structure_id, structure_name, away_status);
                            structure_ids.add(structure_id);

                            if (structure_id_selected) {
                                if (structure_id.equals(structure_id_current)) {
                                    current_in_structures = true;
                                    //
                                    // found the structure_id that we're associated with
                                    // go ahead and update the name and away status
                                    //
                                    SharedPreferences.Editor pref = prefs.edit();
                                    pref.putString(MainActivity.PREFS_STRUCTURE_NAME, structure_name);
                                    pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, away_status);
                                    pref.apply();

                                    last_structure_name = structure_name;
                                    last_away_status = away_status;
                                }
                            }
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "error parsing JSON");
                        return;
                    }

                    if (structure_id_selected) {
                        if (!current_in_structures) {
                            // there is a structure_id selected, but it is no longer in the structures
                            // listed from Nest, so clear it out
                            SharedPreferences.Editor pref = prefs.edit();
                            pref.remove(MainActivity.PREFS_STRUCTURE_ID);
                            pref.remove(MainActivity.PREFS_STRUCTURE_NAME);
                            pref.remove(MainActivity.PREFS_LAST_AWAY_STATUS);
                            pref.apply();
                        }
                    } else {
                        //
                        // No structure_id currently selected, so go ahead and pick the
                        // last structure_id.  This should work for most homes that will
                        // only have one structure_id anyway.
                        //
                        SharedPreferences.Editor pref = prefs.edit();
                        pref.putString(MainActivity.PREFS_STRUCTURE_ID, structure_id);
                        pref.putString(MainActivity.PREFS_STRUCTURE_NAME, structure_name);
                        pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, away_status);
                        pref.apply();

                        last_structure_name = structure_name;
                        last_away_status = away_status;
                    }

                    HashSet<String> stored_structure_ids = StructuresUpdate.getStructureIds(context);
                    for (String id : stored_structure_ids) {
                        if (!structure_ids.contains(id)) {
                            //
                            // if we have a stored id that wasn't in the array Nest just sent us,
                            // then delete it from our database
                            //
                            StructuresUpdate.deleteStructureId(context, id);
                        }
                    }
                    Intent intent = new Intent(GOT_INFO);
                    intent.putExtra("structure_name", last_structure_name);
                    intent.putExtra("away_status", last_away_status);
                    LocalBroadcastManager.getInstance(AppController.getInstance().getApplicationContext())
                            .sendBroadcast(intent);

                }
            }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    if (error.networkResponse != null) {
                        if (debug)
                            Log.d(TAG, "getInfo volley statusCode=" + error.networkResponse.statusCode);

                        Context context = AppController.getInstance().getApplicationContext();

                        if (error.networkResponse.statusCode == HttpStatus.SC_UNAUTHORIZED) {
                            // We must have been de-authorized at the Nest web site
                            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
                            SharedPreferences.Editor pref = prefs.edit();
                            pref.putString(OAuthFlowApp.PREF_ACCESS_TOKEN, "");
                            pref.putString(MainActivity.PREFS_STRUCTURE_ID, "");
                            pref.putString(MainActivity.PREFS_STRUCTURE_NAME, "");
                            pref.putString(MainActivity.PREFS_LAST_AWAY_STATUS, "");
                            pref.apply();

                            HistoryUpdate.add(context, "Lost our Nest authorization");

                            Intent intent = new Intent(LOST_AUTH);
                            LocalBroadcastManager
                                    .getInstance(AppController.getInstance().getApplicationContext())
                                    .sendBroadcast(intent);

                        } else {
                            HistoryUpdate.add(context, error.getLocalizedMessage());
                            VolleyLog.d(TAG, "getInfo Error: " + error.getMessage());
                        }
                    }
                }
            });
    AppController.getInstance().addToRequestQueue(updateStatusReq, tag_update_status);
}

From source file:com.crte.sipstackhome.ui.preferences.PreferencesWrapper.java

/**
 * float?/*from   ww  w .ja  va 2 s .  c om*/
 *
 * @param aPrefs
 * @param key
 * @return
 */
private static Float gPrefFloatValue(SharedPreferences aPrefs, String key) {
    if (aPrefs == null) {
        return FLOAT_PREFS.get(key);
    }
    if (FLOAT_PREFS.containsKey(key)) {
        return aPrefs.getFloat(key, FLOAT_PREFS.get(key));
    }
    if (aPrefs.contains(key)) {
        return aPrefs.getFloat(key, 0.0f);
    }
    return null;
}