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.cerema.cloud2.ui.fragment.OCFileListFragment.java

/**
 * Determines if user set folder to grid or list view. If folder is not set itself,
 * it finds a parent that is set (at least root is set).
 * @param file/*from  w  w  w .  java 2s  .  com*/
 * @return
 */
public boolean isGridViewPreferred(OCFile file) {
    if (file != null) {
        OCFile fileToTest = file;
        OCFile parentDir = null;
        String parentPath = null;
        FileDataStorageManager storageManager = mContainerActivity.getStorageManager();

        SharedPreferences setting = getActivity().getSharedPreferences(GRID_IS_PREFERED_PREFERENCE,
                Context.MODE_PRIVATE);

        if (setting.contains(String.valueOf(fileToTest.getFileId()))) {
            return setting.getBoolean(String.valueOf(fileToTest.getFileId()), false);
        } else {
            do {
                if (fileToTest.getParentId() != FileDataStorageManager.ROOT_PARENT_ID) {
                    parentPath = new File(fileToTest.getRemotePath()).getParent();
                    parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath
                            : parentPath + OCFile.PATH_SEPARATOR;
                    parentDir = storageManager.getFileByPath(parentPath);
                } else {
                    parentDir = storageManager.getFileByPath(OCFile.ROOT_PATH);
                }

                while (parentDir == null) {
                    parentPath = new File(parentPath).getParent();
                    parentPath = parentPath.endsWith(OCFile.PATH_SEPARATOR) ? parentPath
                            : parentPath + OCFile.PATH_SEPARATOR;
                    parentDir = storageManager.getFileByPath(parentPath);
                }
                fileToTest = parentDir;
            } while (endWhile(parentDir, setting));
            return setting.getBoolean(String.valueOf(fileToTest.getFileId()), false);
        }
    } else {
        return false;
    }
}

From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java

@Override
protected void onResume() {
    super.onResume();

    if (PreferenceActivity.prefsMightHaveChanged) {
        PreferenceActivity.prefsMightHaveChanged = false;
        finish();/*from   ww  w. j  ava 2  s .c om*/
        startActivity(getIntent());
    }

    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    showDownloadable.setChecked(prefs.getBoolean(C.SHOW_DOWNLOADABLE, true));

    if (!blockAutoLaunch && getIntent().getBooleanExtra(C.CAN_AUTO_LAUNCH_DICT, true)
            && prefs.contains(C.DICT_FILE) && prefs.contains(C.INDEX_SHORT_NAME)) {
        Log.d(LOG, "Skipping DictionaryManager, going straight to dictionary.");
        startActivity(DictionaryActivity.getLaunchIntent(getApplicationContext(),
                new File(prefs.getString(C.DICT_FILE, "")), prefs.getString(C.INDEX_SHORT_NAME, ""),
                prefs.getString(C.SEARCH_TOKEN, "")));
        finish();
        return;
    }

    // Remove the active dictionary from the prefs so we won't autolaunch
    // next time.
    final Editor editor = prefs.edit();
    editor.remove(C.DICT_FILE);
    editor.remove(C.INDEX_SHORT_NAME);
    editor.remove(C.SEARCH_TOKEN);
    editor.commit();

    application.backgroundUpdateDictionaries(dictionaryUpdater);

    setMyListAdapater();
}

From source file:com.jefftharris.passwdsafe.sync.owncloud.OwncloudProvider.java

/** Update the ownCloud account client based on availability of
 *  authentication information. */
private synchronized void updateOwncloudAcct() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());

    itsAccountName = prefs.getString(PREF_AUTH_ACCOUNT, null);
    String urlStr = prefs.getString(PREF_URL, null);
    PasswdSafeUtil.dbginfo(TAG, "updateOwncloudAcct token %b, url %s", itsAccountName, urlStr);

    String userName = null;//ww w.ja va  2s. com
    Uri url = null;

    if (itsAccountName != null) {
        int pos = itsAccountName.indexOf('@');
        if (pos != -1) {
            userName = itsAccountName.substring(0, pos);

            // Check upgrade
            if ((urlStr == null) && prefs.contains(PREF_USE_HTTPS)) {
                boolean useHttps = prefs.getBoolean(PREF_USE_HTTPS, true);
                urlStr = createUrlFromAccount(itsAccountName, useHttps);

                SharedPreferences.Editor editor = prefs.edit();
                editor.remove(PREF_USE_HTTPS);
                editor.putString(PREF_URL, urlStr);
                editor.apply();
            }

            if (urlStr != null) {
                url = Uri.parse(urlStr);
            }
        } else {
            itsAccountName = null;
        }
    }

    itsUserName = userName;
    itsUrl = url;
    if (itsUrl != null) {
        try {
            updateProviderSyncFreq(itsAccountName);
            requestSync(false);
        } catch (Exception e) {
            Log.e(TAG, "updateOwncloudAcct failure", e);
        }
    } else {
        updateSyncFreq(null, 0);
    }
}

From source file:org.restcomm.app.qoslib.Services.Events.EventUploader.java

/**
 * Loads event requests from storage, and adds it to the queue 
 *//*from   w w  w  . j a va  2s.c o  m*/
protected void loadEventsQueue() {

    ConcurrentLinkedQueue<EventDataEnvelope> eventQueue = owner.getEventManager().getEventQueue();
    if (eventQueue == null) {
        eventQueue = new ConcurrentLinkedQueue<EventDataEnvelope>();
        owner.getEventManager().setEventQueue(eventQueue);
    } else
        return;

    Gson gson = new Gson();
    SharedPreferences secureSettings = MainService.getSecurePreferences(owner);
    if (secureSettings.contains(PreferenceKeys.Miscellaneous.EVENTS_QUEUE)) {
        try {
            String strQueue = secureSettings.getString(PreferenceKeys.Miscellaneous.EVENTS_QUEUE, "");
            //LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "loadQueue", strQueue);
            if (strQueue.length() < 100)
                return;
            JSONArray jsonqueue = new JSONArray(strQueue);
            for (int i = 0; i < jsonqueue.length(); i++) {
                JSONObject jsonRequest = jsonqueue.getJSONObject(i);
                //if(jsonRequest.getString("type").equals(EventDataEnvelope.TAG)) 
                {
                    EventDataEnvelope request = gson.fromJson(jsonRequest.toString(), EventDataEnvelope.class);
                    //EventDataEnvelope request = new EventDataEnvelope(jsonRequest);
                    eventQueue.add(request);
                }
            }
            // remove the oldest events until queue is below 1000
            while (eventQueue.size() > 300)
                eventQueue.poll();
        } catch (JSONException e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "loadEventsQueue",
                    "JSONException loading events from storage", e);
        } catch (Exception e) {
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "loadEventsQueue",
                    "Exception loading events from storage", e);
        }
    }

}

From source file:com.android.mms.transaction.MessagingNotification.java

public static void blockingUpdateNewIccMessageIndicator(Context context, String address, String message,
        int subId, long timeMillis) {
    final Notification.Builder noti = new Notification.Builder(context).setWhen(timeMillis);
    Contact contact = Contact.get(address, false);
    NotificationInfo info = getNewIccMessageNotificationInfo(context, true /* isSms */, address, message,
            null /* subject */, subId, timeMillis, null /* attachmentBitmap */, contact, WorkingMessage.TEXT);
    noti.setSmallIcon(R.drawable.stat_notify_sms);
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    //        TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
    // Update the notification.
    PendingIntent pendingIntent;/*from ww  w . jav a2 s.  com*/
    if (subId == SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
        pendingIntent = PendingIntent.getActivity(context, 0, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    } else {
        // Use requestCode to avoid updating all intents of previous notifications
        pendingIntent = PendingIntent.getActivity(context, ICC_NOTIFICATION_ID_BASE + subId, info.mClickIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
    }
    String title = info.mTitle;
    noti.setContentTitle(title).setContentIntent(pendingIntent)
            //taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
            .setCategory(Notification.CATEGORY_MESSAGE).setPriority(Notification.PRIORITY_DEFAULT);

    int defaults = 0;
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    boolean vibrate = false;
    if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE)) {
        // The most recent change to the vibrate preference is to store a boolean
        // value in NOTIFICATION_VIBRATE. If prefs contain that preference, use that
        // first.
        vibrate = sp.getBoolean(MessagingPreferenceActivity.NOTIFICATION_VIBRATE, false);
    } else if (sp.contains(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN)) {
        // This is to support the pre-JellyBean MR1.1 version of vibrate preferences
        // when vibrate was a tri-state setting. As soon as the user opens the Messaging
        // app's settings, it will migrate this setting from NOTIFICATION_VIBRATE_WHEN
        // to the boolean value stored in NOTIFICATION_VIBRATE.
        String vibrateWhen = sp.getString(MessagingPreferenceActivity.NOTIFICATION_VIBRATE_WHEN, null);
        vibrate = "always".equals(vibrateWhen);
    }
    if (vibrate) {
        defaults |= Notification.DEFAULT_VIBRATE;
    }
    String ringtoneStr = sp.getString(MessagingPreferenceActivity.NOTIFICATION_RINGTONE, null);
    noti.setSound(TextUtils.isEmpty(ringtoneStr) ? null : Uri.parse(ringtoneStr));
    Log.d(TAG, "blockingUpdateNewIccMessageIndicator: adding sound to the notification");

    defaults |= Notification.DEFAULT_LIGHTS;

    noti.setDefaults(defaults);

    // set up delete intent
    noti.setDeleteIntent(PendingIntent.getBroadcast(context, 0, sNotificationOnDeleteIntent, 0));

    final Notification notification;
    // This sets the text for the collapsed form:
    noti.setContentText(info.formatBigMessage(context));

    if (info.mAttachmentBitmap != null) {
        // The message has a picture, show that

        notification = new Notification.BigPictureStyle(noti).bigPicture(info.mAttachmentBitmap)
                // This sets the text for the expanded picture form:
                .setSummaryText(info.formatPictureMessage(context)).build();
    } else {
        // Show a single notification -- big style with the text of the whole message
        notification = new Notification.BigTextStyle(noti).bigText(info.formatBigMessage(context)).build();
    }

    notifyUserIfFullScreen(context, title);
    nm.notify(ICC_NOTIFICATION_ID_BASE + subId, notification);
}

From source file:org.awesomeapp.messenger.service.RemoteImService.java

@Override
public void onCacheWordLocked() {

    //do nothing here?
    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

    if (settings.contains(ImApp.PREFERENCE_KEY_TEMP_PASS)) {
        try {/*from   w w  w  . ja v a  2 s .com*/
            mCacheWord.setPassphrase(settings.getString(ImApp.PREFERENCE_KEY_TEMP_PASS, null).toCharArray());
        } catch (GeneralSecurityException e) {

            Log.d(ImApp.LOG_TAG, "couldn't open cacheword with temp password", e);
        }
    } else if (tempKey != null) {
        openEncryptedStores(tempKey, true);

        ((ImApp) getApplication()).initAccountInfo();

        // Check and login accounts if network is ready, otherwise it's checked
        // when the network becomes available.
        if (mNeedCheckAutoLogin && mNetworkState != NetworkConnectivityReceiver.State.NOT_CONNECTED) {
            mNeedCheckAutoLogin = !autoLogin();
            ;
        }
    }

}

From source file:net.zorgblub.typhon.Configuration.java

public List<HighLight> getHightLights(String fileName) {
    SharedPreferences prefs = getPrefsForBook(fileName);

    if (prefs.contains(KEY_HIGHLIGHTS)) {
        return HighLight.fromJSON(fileName, prefs.getString(KEY_HIGHLIGHTS, "[]"));
    }/* w  ww. j av  a 2 s  . c o m*/

    return new ArrayList<>();
}

From source file:ngoc.com.pedometer.ui.Fragment_Overview.java

@Override
public void onResume() {
    super.onResume();
    //        getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);

    Database db = Database.getInstance(getActivity());

    if (BuildConfig.DEBUG)
        db.logState();/*from w w  w  .  j a v a2 s .co  m*/
    // read todays offset
    todayOffset = db.getSteps(Util.getToday());

    SharedPreferences prefs = getActivity().getSharedPreferences("pedometer", Context.MODE_PRIVATE);

    goal = prefs.getInt("goal", Fragment_Settings.DEFAULT_GOAL);
    since_boot = db.getCurrentSteps(); // do not use the value from the sharedPreferences
    int pauseDifference = since_boot - prefs.getInt("pauseCount", since_boot);

    // register a sensorlistener to live update the UI if a step is taken
    if (!prefs.contains("pauseCount")) {
        SensorManager sm = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        Sensor sensor = sm.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
        if (sensor == null) {
            new AlertDialog.Builder(getActivity()).setTitle(R.string.no_sensor)
                    .setMessage(R.string.no_sensor_explain)
                    .setOnDismissListener(new DialogInterface.OnDismissListener() {
                        @Override
                        public void onDismiss(final DialogInterface dialogInterface) {
                            getActivity().finish();
                        }
                    }).setNeutralButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialogInterface, int i) {
                            dialogInterface.dismiss();
                        }
                    }).create().show();
        } else {
            sm.registerListener(this, sensor, SensorManager.SENSOR_DELAY_UI, 0);
        }
    }

    since_boot -= pauseDifference;

    total_start = db.getTotalWithoutToday();
    total_days = db.getDays();

    db.close();

    stepsDistanceChanged();
}

From source file:com.example.administrator.myapplication2._2_exercise._2_Status_heart.fragments.LeftFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout._2_status_heart, container, false);

    SharedPreferences myPrefs = getActivity().getSharedPreferences("alert", Context.MODE_PRIVATE);
    if ((myPrefs != null) && (myPrefs.contains("alert"))) {
        alert = myPrefs.getBoolean("alert", false);
    }//from w w w  .  ja v a  2  s .  c o m

    mTextChat = (TextView) rootView.findViewById(R.id.text_chat);
    mTextChat.setMaxLines(1000);
    mTextChat.setVerticalScrollBarEnabled(true);
    mTextChat.setMovementMethod(new ScrollingMovementMethod());

    //mEditChat = (EditText) rootView.findViewById(R.id.edit_chat);
    //mEditChat.setOnEditorActionListener(mWriteListener);

    mBtnSend = (Button) rootView.findViewById(R.id.button_send);
    mBtnSend.setOnClickListener(this);

    handler = new MyHandler();
    progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar2);

    new Thread() {

        @Override

        public void run() {
            try {
                while (true) {
                    sleep(1000);
                    handler.sendMessage(new Message());

                    if (threadBool == false) {
                        break;
                    }

                }
            } catch (InterruptedException e) {

                e.printStackTrace();
            }
        }
    }.start();

    /*///////?//////////*/

    heartRateList = new ArrayList<>();
    tvTime = (TextView) rootView.findViewById(R.id.tvTime);
    ibPause = (ImageButton) rootView.findViewById(R.id.ibPause);
    ibStop = (ImageButton) rootView.findViewById(R.id.ibStop);

    ibPause.setOnClickListener(this);
    ibStop.setOnClickListener(this);

    m_display_run = new Runnable() {
        public void run() {
            // ? ? .
            tvTime.setText(m_display_string);
        }
    };

    /*gps*/
    //  ? ?  -   
    mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);

    arrayPoints = new ArrayList<LatLng>();
    arrayPoints_network = new ArrayList<LatLng>();

    postJsonData1();

    //  ?   
    startLocationService();
    return rootView;
}

From source file:com.ppdl.microphone.MainActivity.java

public void bindParams(Intent intent) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    if (sp.getBoolean("tips_sound", true)) {
        intent.putExtra(Constant.EXTRA_SOUND_START, R.raw.bdspeech_recognition_start);
        intent.putExtra(Constant.EXTRA_SOUND_END, R.raw.bdspeech_speech_end);
        intent.putExtra(Constant.EXTRA_SOUND_SUCCESS, R.raw.bdspeech_recognition_success);
        intent.putExtra(Constant.EXTRA_SOUND_ERROR, R.raw.bdspeech_recognition_error);
        intent.putExtra(Constant.EXTRA_SOUND_CANCEL, R.raw.bdspeech_recognition_cancel);
    }/*  ww  w  .  j  a va  2s.  c om*/
    if (sp.contains(Constant.EXTRA_INFILE)) {
        String tmp = sp.getString(Constant.EXTRA_INFILE, "").replaceAll(",.*", "").trim();
        intent.putExtra(Constant.EXTRA_INFILE, tmp);
    }
    if (sp.getBoolean(Constant.EXTRA_OUTFILE, false)) {
        intent.putExtra(Constant.EXTRA_OUTFILE, "sdcard/outfile.pcm");
    }
    if (sp.contains(Constant.EXTRA_SAMPLE)) {
        String tmp = sp.getString(Constant.EXTRA_SAMPLE, "").replaceAll(",.*", "").trim();
        if (null != tmp && !"".equals(tmp)) {
            intent.putExtra(Constant.EXTRA_SAMPLE, Integer.parseInt(tmp));
        }
    }
    if (sp.contains(Constant.EXTRA_LANGUAGE)) {
        String tmp = sp.getString(Constant.EXTRA_LANGUAGE, "").replaceAll(",.*", "").trim();
        if (null != tmp && !"".equals(tmp)) {
            intent.putExtra(Constant.EXTRA_LANGUAGE, tmp);
        }
    }
    if (sp.contains(Constant.EXTRA_NLU)) {
        String tmp = sp.getString(Constant.EXTRA_NLU, "").replaceAll(",.*", "").trim();
        if (null != tmp && !"".equals(tmp)) {
            intent.putExtra(Constant.EXTRA_NLU, tmp);
        }
    }

    if (sp.contains(Constant.EXTRA_VAD)) {
        String tmp = sp.getString(Constant.EXTRA_VAD, "").replaceAll(",.*", "").trim();
        if (null != tmp && !"".equals(tmp)) {
            intent.putExtra(Constant.EXTRA_VAD, tmp);
        }
    }

    String prop = null;
    if (sp.contains(Constant.EXTRA_PROP)) {
        String tmp = sp.getString(Constant.EXTRA_PROP, "").replaceAll(",.*", "").trim();
        if (null != tmp && !"".equals(tmp)) {
            Log.i(TAG, "=======$====" + tmp);
            intent.putExtra(Constant.EXTRA_PROP, Integer.parseInt(tmp));
            prop = tmp;
        }
    }
    // offline asr
    {
        intent.putExtra("sample", 16000); // ? 16000 
        intent.putExtra("language", "cmn-Hans-CN"); // ??
        intent.putExtra("prop", 20000);
        Log.i(TAG, "============= " + Environment.getExternalStorageDirectory().getPath());
        intent.putExtra(Constant.EXTRA_OFFLINE_ASR_BASE_FILE_PATH,
                Environment.getExternalStorageDirectory().getPath() + "/s_1");
        intent.putExtra(Constant.EXTRA_LICENSE_FILE_PATH,
                Environment.getExternalStorageDirectory().getPath() + "/temp_license_2016-04-18");

        ///if (null != prop) {
        //    int propInt = Integer.parseInt(prop);
        //   if (propInt == 10060) {
        intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH,
                Environment.getExternalStorageDirectory().getPath() + "/s_2_Navi");
        ////   } else if (propInt == 20000) {
        intent.putExtra(Constant.EXTRA_OFFLINE_LM_RES_FILE_PATH,
                Environment.getExternalStorageDirectory().getPath() + "/s_2_InputMethod");
        //   }
        //}
        intent.putExtra(Constant.EXTRA_OFFLINE_SLOT_DATA, buildTestSlotData());
    }
}