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:net.gsantner.opoc.preference.SharedPreferencesPropertyBackend.java

public boolean isPrefSet(final SharedPreferences pref, @StringRes int stringKeyResourceId) {
    return pref.contains(rstr(stringKeyResourceId));
}

From source file:com.mdlive.myhealth.MedicalHistoryActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mdlive_tab_activity);
    clearMinimizedTime();/*from w  ww .  j  ava 2s  .co  m*/
    this.setTitle(getString(R.string.mdl_my_health));
    setDrawerLayout((DrawerLayout) findViewById(R.id.drawer_layout));

    final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        setHeaderTitle(R.string.mdl_medical_history_txt);
    }

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setId(R.id.viewpager);
    if (viewPager != null) {
        setupViewPager(viewPager);

    }

    // Initializing the "GOOGLE_FIT_SYNC_BTN_CLICKED" shared preference to 'false'. This preference protects
    // the user from being exposed to continuance selection prompts when there is more than one Gmail acct on the device.
    SharedPreferences sharedPref = getSharedPreferences(PreferenceConstants.USER_PREFERENCES,
            Context.MODE_PRIVATE);
    SharedPreferences userPrefs = getSharedPreferences(
            sharedPref.getString(PreferenceConstants.USER_UNIQUE_ID, AppSpecificConfig.DEFAULT_USER_ID),
            Context.MODE_PRIVATE);
    if (!userPrefs.contains(PreferenceConstants.GOOGLE_FIT_SYNC_BTN_CLICKED)) {
        SharedPreferences.Editor editor = userPrefs.edit();
        editor.putBoolean(PreferenceConstants.GOOGLE_FIT_SYNC_BTN_CLICKED, false);
    }

    final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
    //tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    //tabLayout.setTabGravity(TabLayout.GRAVITY_FILL | TabLayout.GRAVITY_CENTER);
    tabLayout.setupWithViewPager(viewPager);

    if (getIntent().getExtras() != null && getIntent().hasExtra(SELECTED_TAB)) {
        viewPager.setCurrentItem(getIntent().getIntExtra(SELECTED_TAB, 0));
        viewPager.invalidate();
    }
    if (savedInstanceState == null) {
        // **** DEBUG ONLY.   o.uwechue
        Log.e("Medical History", "+++++++++++++++++\nAbout to create nav drawer");
        getSupportFragmentManager().beginTransaction()
                .add(R.id.dash_board__left_container, NavigationDrawerFragment.newInstance(), LEFT_MENU)
                .commit();

        getSupportFragmentManager().beginTransaction()
                .add(R.id.dash_board__right_container, NotificationFragment.newInstance(), RIGHT_MENU).commit();
    }
}

From source file:net.texh.cordovapluginstepcounter.StepCounterService.java

@Override
public void onSensorChanged(SensorEvent sensorEvent) {
    //Log.i(TAG, "onSensorChanged event!");
    Integer totalSteps = 0;/*  ww w  .  j  av a 2 s  .c o m*/
    Integer steps = Math.round(sensorEvent.values[0]);
    Integer daySteps = 0;
    Integer dayOffset = 0;

    Date currentDate = new Date();
    SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    String currentDateString = dateFormatter.format(currentDate);
    SharedPreferences sharedPref = getSharedPreferences(CordovaStepCounter.USER_DATA_PREF,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();

    JSONObject pData = new JSONObject();
    JSONObject dayData = new JSONObject();
    if (sharedPref.contains(CordovaStepCounter.PEDOMETER_HISTORY_PREF)) {
        String pDataString = sharedPref.getString(CordovaStepCounter.PEDOMETER_HISTORY_PREF, "{}");
        try {
            pData = new JSONObject(pDataString);
            Log.d(TAG, " got json shared prefs " + pData.toString());
        } catch (JSONException err) {
            Log.d(TAG, " Exception while parsing json string : " + pDataString);
        }
    }

    //Get the datas previously stored for today
    if (pData.has(currentDateString)) {
        try {
            dayData = pData.getJSONObject(currentDateString);
            dayOffset = dayData.getInt("offset");
            daySteps = dayData.getInt("steps");
            haveSetOffset = true;

            //If steps is less thant dayOffset, means that dayOffset is not correct (due to reboot in the middle of the day)
            if (steps < dayOffset) {
                haveSetOffset = false;
            }
        } catch (JSONException err) {
            Log.e(TAG, "Exception while getting Object from JSON for " + currentDateString);
        }
    } else {
        // If there is no data, we will have to save offset
        haveSetOffset = false;
    }

    //Counter += 1
    Integer stepsCounted = CordovaStepCounter.getTotalCount(sharedPref);
    stepsCounted += 1;
    CordovaStepCounter.setTotalCount(sharedPref, stepsCounted);

    //If offset has not been set or if saved offset is greater than today offset
    if (!haveSetOffset) {
        //Change offset for current count
        dayOffset = steps - daySteps;
        //Add one to steps (=1 if offset not set, or +1 if steps count has been resetted by a phone restart)
        haveSetOffset = true;
        Log.i(TAG, "  * Updated offset: " + dayOffset);
    }

    //First 'steps' is 0 an not 1
    daySteps = (steps + 1) - dayOffset;
    //Log all this
    Log.i(TAG, "** daySteps :" + daySteps + " ** stepCounted :" + stepsCounted);

    //Save calculated values to SharedPreferences
    try {
        dayData.put("steps", daySteps);
        dayData.put("offset", dayOffset);
        pData.put(currentDateString, dayData);
    } catch (JSONException err) {
        Log.e(TAG, "Exception while setting int in JSON for " + currentDateString);
    }
    editor.putString(CordovaStepCounter.PEDOMETER_HISTORY_PREF, pData.toString());
    editor.commit();
}

From source file:com.nsqre.insquare.Utilities.PushNotification.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 * Manages how the notification will be shown in the notification bar.
 * @param message GCM message received./*from   w  w w  . jav  a2  s. c o m*/
 */
private void sendNotification(String message, String squareName, String squareId) {
    Intent intent = new Intent(this, BottomNavActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    SharedPreferences notificationPreferences = getSharedPreferences("NOTIFICATION_MAP", MODE_PRIVATE);
    int notificationCount = 0;
    int squareCount = notificationPreferences.getInt("squareCount", 0);

    if (squareId.equals(notificationPreferences.getString("actualSquare", ""))) {
        return;
    }

    if (!notificationPreferences.contains(squareId)) {
        notificationPreferences.edit().putInt("squareCount", squareCount + 1).apply();
    }
    notificationPreferences.edit().putInt(squareId, notificationPreferences.getInt(squareId, 0) + 1).apply();

    for (String square : notificationPreferences.getAll().keySet()) {
        if (!"squareCount".equals(square) && !"actualSquare".equals(square)) {
            notificationCount += notificationPreferences.getInt(square, 0);
        }
    }

    squareCount = notificationPreferences.getInt("squareCount", 0);

    Log.d(TAG, notificationPreferences.getAll().toString());

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
    notificationBuilder.setSmallIcon(R.drawable.nsqre_map_pin_empty_inside);
    notificationBuilder.setColor(ContextCompat.getColor(getApplicationContext(), R.color.colorAccent));

    if (squareCount == 1) {
        SharedPreferences messagePreferences = getSharedPreferences(squareId, MODE_PRIVATE);
        intent.putExtra("squareId", squareId);
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        messagePreferences.edit().putString(String.valueOf(notificationCount), message).commit();
        if (messagePreferences.getAll().size() <= 6) {
            for (int i = 1; i <= messagePreferences.getAll().keySet().size(); i++) {
                inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), ""));
            }
        } else {
            for (int i = messagePreferences.getAll().size() - 6; i <= messagePreferences.getAll().keySet()
                    .size(); i++) {
                inboxStyle.addLine(messagePreferences.getString(String.valueOf(i), ""));
            }
        }
        notificationBuilder.setContentTitle(squareName);
        notificationBuilder.setStyle(inboxStyle.setBigContentTitle(squareName).setSummaryText("inSquare"));
        notificationBuilder.setContentText(
                notificationCount > 1 ? "Hai " + notificationCount + " nuovi messaggi" : message);
    } else {
        intent.putExtra("map", 0);
        intent.removeExtra("squareId");
        notificationBuilder.setContentTitle("inSquare");
        notificationBuilder
                .setContentText("Hai " + (notificationCount) + " nuovi messaggi in " + squareCount + " piazze");
    }
    notificationBuilder.setAutoCancel(true);
    notificationBuilder.setSound(defaultSoundUri);
    notificationBuilder.setVibrate(new long[] { 300, 300, 300, 300, 300 });
    notificationBuilder.setLights(Color.RED, 1000, 3000);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    notificationBuilder.setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    updateSquares("", "", "update");

    SharedPreferences mutePreferences = getSharedPreferences("NOTIFICATION_MUTE_MAP", MODE_PRIVATE);

    if (mutePreferences.contains(squareId)) {

        String expireDate = mutePreferences.getString(squareId, "");

        long myExpireDate = Long.parseLong(expireDate, 10);
        if (myExpireDate < (new Date().getTime())) {
            mutePreferences.edit().remove(squareId).apply();
            notificationManager.notify(0, notificationBuilder.build());
        }

    } else {

        notificationManager.notify(0, notificationBuilder.build());
    }

}

From source file:com.teinproductions.tein.papyrosprogress.MainActivity.java

private void checkNotificationsAsked() {
    @SuppressWarnings("deprecation")
    final SharedPreferences oldSharedPref = getSharedPreferences(Constants.SHARED_PREFERENCES, MODE_PRIVATE);
    final SharedPreferences defaultSharedPref = PreferenceManager.getDefaultSharedPreferences(this);

    if (oldSharedPref.contains(Constants.NOTIFICATION_ASKED_PREFERENCE)) {
        // The old preferences have to be copied over to the new default shared preferences
        SharedPreferences.Editor editor = defaultSharedPref.edit();
        editor.putBoolean(Constants.NOTIFICATION_PREFERENCE,
                oldSharedPref.getBoolean(Constants.NOTIFICATION_PREFERENCE, true));
        editor.putInt(Constants.CACHED_BLOG_AMOUNT, oldSharedPref.getInt(Constants.CACHED_BLOG_AMOUNT, 0));

        for (int id : AbstractProgressWidget.getAppWidgetLargeIds(this, AppWidgetManager.getInstance(this))) {
            editor.putInt(Constants.TEXT_SIZE_PREFERENCE + id,
                    oldSharedPref.getInt(Constants.TEXT_SIZE_PREFERENCE + id, 24));
            editor.putString(Constants.MILESTONE_WIDGET_PREFERENCE + id,
                    oldSharedPref.getString(Constants.MILESTONE_WIDGET_PREFERENCE + id, "Version 0.1"));
        }/*from  ww w . ja  v a2 s.c om*/
        for (int id : AbstractProgressWidget.getAppWidgetSmallIds(this, AppWidgetManager.getInstance(this))) {
            editor.putInt(Constants.TEXT_SIZE_PREFERENCE + id,
                    oldSharedPref.getInt(Constants.TEXT_SIZE_PREFERENCE + id, 24));
            editor.putString(Constants.MILESTONE_WIDGET_PREFERENCE + id,
                    oldSharedPref.getString(Constants.MILESTONE_WIDGET_PREFERENCE + id, "Version 0.1"));
        }
        editor.apply();

        // Clear the old shared preferences
        oldSharedPref.edit().clear().apply();
    } else if (!defaultSharedPref.contains(Constants.NOTIFICATION_PREFERENCE)) {
        new AlertDialog.Builder(this).setTitle(getString(R.string.notifications))
                .setMessage(getString(R.string.notification_dialog_message))
                .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        defaultSharedPref.edit().putBoolean(Constants.NOTIFICATION_PREFERENCE, true).apply();
                        AlarmUtils.setAlarm(MainActivity.this);
                        invalidateOptionsMenu();
                    }
                }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        defaultSharedPref.edit().putBoolean(Constants.NOTIFICATION_PREFERENCE, false).apply();
                        AlarmUtils.reconsiderSettingAlarm(MainActivity.this);
                        invalidateOptionsMenu();
                    }
                }).create().show();
    }
}

From source file:com.example.administrator.myapplication2._5_Group._5_Group.RightFragment.java

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

    View rootView = inflater.inflate(R.layout._5_community_right, container, false);
    switchBtn = (Switch) rootView.findViewById(R.id.switchBtn);

    SharedPreferences myPrefs = this.getActivity().getSharedPreferences("switch", Context.MODE_PRIVATE);
    if ((myPrefs != null) && (myPrefs.contains("switch"))) {
        switchbool = myPrefs.getBoolean("switch", false);
    }/*  w  w w .  j a  v a  2  s  . com*/

    switchBtn.setChecked(switchbool);
    listItem = new ArrayList<HashMap<String, String>>();

    switchBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences myPrefs = getActivity().getSharedPreferences("switch", Context.MODE_PRIVATE);
            SharedPreferences.Editor myEditor = myPrefs.edit();
            if (isChecked == true) {
                /*switch  ?*/
                myEditor.putBoolean("switch", true);
                myEditor.commit();
                /*??*/
            } else if (isChecked == false) {
                setGpsNull();
                myEditor.putBoolean("switch", false);
                myEditor.commit();
            }
        }

    });

    SharedPreferences myPrefs2 = this.getActivity().getSharedPreferences("login", Context.MODE_PRIVATE);
    if ((myPrefs2 != null) && (myPrefs2.contains("id"))) {
        id = myPrefs2.getString("id", "");
        name = myPrefs2.getString("name", "");
    }

    getGroupName();

    // ? ? 
    map = ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map2)).getMap();
    map.setMyLocationEnabled(true);
    map.setOnMarkerClickListener(onMarkerClickedListener); // ? 
    /*gps*/
    //  ? ?  -   
    mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    if (switchbool == true) {
        //  ?   
        startLocationService();
    }

    return rootView;
}

From source file:com.geoffreybuttercrumbs.arewethereyet.DrawerFragment.java

private Location retrieveRecent(int index) {
    SharedPreferences prefs = getActivity().getSharedPreferences("AreWeThereYet", Context.MODE_WORLD_WRITEABLE);
    Location location = new Location("POINT_LOCATION");
    location.setLatitude(0);//from w w  w. j  ava2 s  .c  om
    location.setLongitude(0);
    if (prefs.contains(POINT_LATITUDE_KEY + index)) {
        location.setLatitude(prefs.getFloat(POINT_LATITUDE_KEY + index, 0));
    }
    if (prefs.contains(POINT_LONGITUDE_KEY + index)) {
        location.setLongitude(prefs.getFloat(POINT_LONGITUDE_KEY + index, 0));
    }
    return location;
}

From source file:com.geoffreybuttercrumbs.arewethereyet.DrawerFragment.java

private Location retrieveSaved(int index) {
    SharedPreferences prefs = getActivity().getSharedPreferences("AreWeThereYet", Context.MODE_WORLD_WRITEABLE);
    Location location = new Location("POINT_LOCATION");
    location.setLatitude(0);// ww  w.j av a 2s . c o m
    location.setLongitude(0);
    if (prefs.contains(SAVED_LATITUDE_KEY + index)) {
        location.setLatitude(prefs.getFloat(SAVED_LATITUDE_KEY + index, 0));
    }
    if (prefs.contains(SAVED_LONGITUDE_KEY + index)) {
        location.setLongitude(prefs.getFloat(SAVED_LONGITUDE_KEY + index, 0));
    }
    return location;
}

From source file:net.xisberto.phonetodesktop.GoogleTasksActivity.java

private void updateSetting(String key) {
    SharedPreferences settings_old = getPreferences(MODE_PRIVATE);
    if (settings_old.contains(key)) {
        String value = settings_old.getString(key, "");
        apply(settings.edit().putString(key, value));
        apply(settings_old.edit().remove(key));
    }//from w  w  w. ja v  a2s.  co m
}

From source file:com.gcm.client.GcmHelper.java

/**
 * Initialize the GcmHelper class. To be called from the application class onCreate or from the
 * onCreate of the main activity/*from w ww  .  j  a v a 2 s .  co m*/
 *
 * @param context An instance of the Application Context
 */
public synchronized void init(@NonNull Context context) {
    if (!isGooglePlayservicesAvailable(context)) {
        throw new IllegalArgumentException("Not using the recommended Play Services version");
    }
    //get the GCM sender id from strings.xml
    if (TextUtils.isEmpty(senderID)) {
        int id = context.getResources().getIdentifier("gcm_authorized_entity", "string",
                context.getPackageName());
        senderID = context.getResources().getString(id);
    }

    if (TextUtils.isEmpty(senderID)) {
        throw new IllegalArgumentException("No SenderId provided!! Cannot instantiate");
    }

    SharedPreferences localPref = getSharedPreference(context);
    //get topics array
    if (localPref.contains(PREF_KEY_SUBSCRIPTION)) {
        String subscription = localPref.getString(PREF_KEY_SUBSCRIPTION, null);
        if (!TextUtils.isEmpty(subscription)) {
            try {
                JSONArray array = new JSONArray(subscription);
                int length = array.length();
                topics = new ArrayList<>();
                for (int i = 0; i < length; i++) {
                    topics.add(array.getString(i));
                }
            } catch (JSONException ignored) {
                if (DEBUG_ENABLED)
                    Log.e(TAG, "init: while processing subscription list", ignored);
            }
        }
    }

    boolean registrationReq = true;
    if (localPref.contains(PREF_KEY_TOKEN)) {
        pushToken = localPref.getString(PREF_KEY_TOKEN, null);
        if (!TextUtils.isEmpty(pushToken)) {
            registrationReq = false;
            //don't pass token if already present
        }
    }
    if (registrationReq) {
        //register for push token
        Intent registration = new Intent(context, RegistrationIntentService.class);
        registration.setAction(RegistrationIntentService.ACTION_REGISTER);
        context.startService(registration);
    }
    //check if debug build and enable DEBUG MODE
    DEBUG_ENABLED = (0 != (context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE));
    initialized = true;
}