Java Code Examples for android.content.SharedPreferences

The following are top voted examples for showing how to use android.content.SharedPreferences. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: speedr   File: Prefs.java   Source Code and License 9 votes vote down vote up
private static SharedPreferences prefs(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context);
}
 
Example 2
Project: Kids-Portal-Android   File: helper_browser.java   Source Code and License 6 votes vote down vote up
public static String tab_5 (Activity activity) {
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(activity);
    String s;

    final String tab_string = sharedPref.getString("tab_4", "");

    try {
        if (tab_string.isEmpty()) {
            s = activity.getString(R.string.context_tab);
        } else {
            s = tab_string;
        }
    } catch (Exception e) {
        Log.e("KidsPortal", "Unable to get String", e);
        s = activity.getString(R.string.context_tab);
    }
    return s;
}
 
Example 3
Project: android-dev-challenge   File: SettingsFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreatePreferences(Bundle bundle, String s) {
    // Add 'general' preferences, defined in the XML file
    addPreferencesFromResource(R.xml.pref_general);

    SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
    PreferenceScreen prefScreen = getPreferenceScreen();
    int count = prefScreen.getPreferenceCount();
    for (int i = 0; i < count; i++) {
        Preference p = prefScreen.getPreference(i);
        if (!(p instanceof CheckBoxPreference)) {
            String value = sharedPreferences.getString(p.getKey(), "");
            setPreferenceSummary(p, value);
        }
    }
}
 
Example 4
Project: chapp-messenger   File: LoginActivity.java   Source Code and License 6 votes vote down vote up
private void getInformationFromFB(String UID) {
    dbr_users.child(UID).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            email = (String) dataSnapshot.child("mail").getValue();
            name = (String) dataSnapshot.child("name").getValue();
            username = (String) dataSnapshot.child("username").getValue();
            password = (String) dataSnapshot.child("password").getValue();
            telefonnummer = (String) dataSnapshot.child("telefonnummer").getValue();

            SharedPreferences.Editor editor = getSharedPreferences("CHAPP_PREFS", Context.MODE_PRIVATE).edit();
            editor.putString("email", email);
            editor.putString("name", name);
            editor.putString("username", username);
            editor.putString("telefonnummer", telefonnummer);
            editor.putString("password", password);
            editor.commit();
        };

        @Override
        public void onCancelled(DatabaseError databaseError) {
            // ...
        }
    });
}
 
Example 5
Project: android-dev-challenge   File: SunshinePreferences.java   Source Code and License 6 votes vote down vote up
/**
 * Returns the location coordinates associated with the location. Note that there is a
 * possibility that these coordinates may not be set, which results in (0,0) being returned.
 * Interestingly, (0,0) is in the middle of the ocean off the west coast of Africa.
 *
 * @param context used to access SharedPreferences
 * @return an array containing the two coordinate values for the user's preferred location
 */
public static double[] getLocationCoordinates(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);

    double[] preferredCoordinates = new double[2];

    /*
     * This is a hack we have to resort to since you can't store doubles in SharedPreferences.
     *
     * Double.doubleToLongBits returns an integer corresponding to the bits of the given
     * IEEE 754 double precision value.
     *
     * Double.longBitsToDouble does the opposite, converting a long (that represents a double)
     * into the double itself.
     */
    preferredCoordinates[0] = Double
             .longBitsToDouble(sp.getLong(PREF_COORD_LAT, Double.doubleToRawLongBits(0.0)));
    preferredCoordinates[1] = Double
            .longBitsToDouble(sp.getLong(PREF_COORD_LONG, Double.doubleToRawLongBits(0.0)));

    return preferredCoordinates;
}
 
Example 6
Project: keepass2android   File: AccessManager.java   Source Code and License 6 votes vote down vote up
public static Set<String> getAllHostPackages(Context ctx)
{
	SharedPreferences prefs = ctx.getSharedPreferences("KP2A.PluginAccess.hosts", Context.MODE_PRIVATE);
	Set<String> result = new HashSet<String>();
	for (String host: prefs.getAll().keySet())
	{
		try
		{
			PackageInfo info = ctx.getPackageManager().getPackageInfo(host, PackageManager.GET_META_DATA);
			//if we get here, the package is still there
			result.add(host);
		}
		catch (PackageManager.NameNotFoundException e)
		{
			//host gone. ignore.
		}
	}
	return result;
	
}
 
Example 7
Project: Mobike   File: PersistentCookieStore.java   Source Code and License 6 votes vote down vote up
@Override
public boolean clearExpired(Date date) {
    boolean clearedAny = false;
    SharedPreferences.Editor prefsWriter = cookiePrefs.edit();

    for (ConcurrentHashMap.Entry<String, Cookie> entry : cookies.entrySet()) {
        String name = entry.getKey();
        Cookie cookie = entry.getValue();
        if (cookie.isExpired(date)) {
            // Clear cookies from local store
            cookies.remove(name);

            // Clear cookies from persistent store
            prefsWriter.remove(COOKIE_NAME_PREFIX + name);

            // We've cleared at least one
            clearedAny = true;
        }
    }

    // Update names in persistent store
    if (clearedAny) {
        prefsWriter.putString(COOKIE_NAME_STORE, TextUtils.join(",", cookies.keySet()));
    }
    prefsWriter.commit();

    return clearedAny;
}
 
Example 8
Project: DAPNETApp   File: MainActivity.java   Source Code and License 6 votes vote down vote up
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    Menu nv = navigationView.getMenu();
    MenuItem mloginstatus = nv.findItem(R.id.nav_loginstatus);
    SharedPreferences sharedPref = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    loggedIn = sharedPref.getBoolean("isLoggedIn", false);
    mServer = sharedPref.getString("server", null);

    if (loggedIn) {
        mloginstatus.setTitle(R.string.nav_logout);
        Log.i(TAG, "User is logged in!");
    } else {
        mloginstatus.setTitle(R.string.nav_login);
        Log.i(TAG, "User is not logged in!");
    }
    if (mServer != null) {
        setVersion(mServer);
    } else {
        setVersion("http://hampager.de:8080");
        //if mServer == null
        // setVersion("http://dapnet.db0sda.ampr.org:8080")
    }

    return true;
}
 
Example 9
Project: memento-app   File: StorageHelper.java   Source Code and License 6 votes vote down vote up
public static void setPersonGroupName(String personGroupIdToAdd, String personGroupName, Context context) {
    SharedPreferences personGroupIdNameMap =
            context.getSharedPreferences("PersonGroupIdNameMap", Context.MODE_PRIVATE);

    SharedPreferences.Editor personGroupIdNameMapEditor = personGroupIdNameMap.edit();
    personGroupIdNameMapEditor.putString(personGroupIdToAdd, personGroupName);
    personGroupIdNameMapEditor.commit();

    Set<String> personGroupIds = getAllPersonGroupIds(context);
    Set<String> newPersonGroupIds = new HashSet<>();
    for (String personGroupId: personGroupIds) {
        newPersonGroupIds.add(personGroupId);
    }
    newPersonGroupIds.add(personGroupIdToAdd);
    SharedPreferences personGroupIdSet =
            context.getSharedPreferences("PersonGroupIdSet", Context.MODE_PRIVATE);
    SharedPreferences.Editor personGroupIdSetEditor = personGroupIdSet.edit();
    personGroupIdSetEditor.putStringSet("PersonGroupIdSet", newPersonGroupIds);
    personGroupIdSetEditor.commit();
}
 
Example 10
Project: Shared-Route   File: PayBillActivity.java   Source Code and License 6 votes vote down vote up
private void postInfo() {
    if (mAuthTask != null) {
        return;
    }
    showProgress(true);
    String payPath = "";
    RadioButton zhifubao = (RadioButton)findViewById(R.id.zhifubao);
    RadioButton wechat = (RadioButton)findViewById(R.id.wechat);
    if (zhifubao.isChecked()){
        payPath = "zhifubao";
    } else if (wechat.isChecked()) {
        payPath="wechat";
    }
    SharedPreferences sp = getSharedPreferences("now_account", Context.MODE_PRIVATE);
    stuNum=sp.getString("now_stu_num",null);
    Bundle bundle = getIntent().getExtras();
    mAuthTask = new PostTask(bundle.getString("money"),bundle.getString("name"),
            bundle.getString("phone"),bundle.getString("num"),bundle.getString("packsort"),
            bundle.getString("pickupplace"),bundle.getString("delieverplace"),
            bundle.getString("pickuptime"),bundle.getString("delievertime"),
            payPath,bundle.getString("remark"),stuNum,bundle.getString("securitymoney"));
    mAuthTask.execute((Void) null);

}
 
Example 11
Project: TherapyGuide   File: SettingsFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Define the settings file
    getPreferenceManager().setSharedPreferencesName(MainActivity.PREFERENCES);
    getPreferenceManager().setSharedPreferencesMode(Context.MODE_PRIVATE);

    // Load the preferences from an XML resource
    addPreferencesFromResource(R.xml.preferences);

    // Set the summary for the diary reminder time
    SharedPreferences sharedPreferences = getActivity()
            .getSharedPreferences(MainActivity.PREFERENCES, Context.MODE_PRIVATE);
    setDiaryReminderTimeSummary(sharedPreferences);

    // Prepare alarm
    Intent intent = new Intent(getActivity(), AlarmHandler.class);
    intent.setAction(AlarmHandler.DIARY_ALERT);
    mAlarmIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
    mAlarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

    mReceiver = new ComponentName(getActivity(), BootHandler.class);
    mPackageManager = getActivity().getPackageManager();
}
 
Example 12
Project: appinventor-extensions   File: Pedometer.java   Source Code and License 6 votes vote down vote up
/**
 * Saves the pedometer state to shared preferences.
 */
@SimpleFunction(description = "Saves the pedometer state to the phone. Permits " +
  "permits accumulation of steps and distance between invocations of an App that uses " +
  "the pedometer. Different Apps will have their own saved state.")
public void Save() {
  // Store preferences
  SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
  SharedPreferences.Editor editor = settings.edit();
  editor.putFloat("Pedometer.stridelength", strideLength);
  editor.putFloat("Pedometer.distance", totalDistance);
  editor.putInt("Pedometer.prevStepCount", numStepsRaw);
  if (pedometerPaused) {
    editor.putLong("Pedometer.clockTime", prevStopClockTime);
  } else {
    editor.putLong("Pedometer.clockTime", prevStopClockTime +
        (System.currentTimeMillis() - startTime));
  }
  editor.putLong("Pedometer.closeTime", System.currentTimeMillis());
  editor.commit();
  Log.d(TAG, "Pedometer state saved.");
}
 
Example 13
Project: Android_watch_magpie   File: MagpieActivity.java   Source Code and License 6 votes vote down vote up
private void recreateAgents(SharedPreferences settings) {
    Message request = Message.obtain();
    request.what = Environment.RECREATE_AGENTS;
    request.replyTo = replyMessenger;

    Bundle bundle = new Bundle();

    HashSet<String> agentNamesFromActivity = (HashSet<String>)
            settings.getStringSet(ACTIVITY_NAME, new HashSet<String>());
    bundle.putSerializable(AGENT_NAMES, agentNamesFromActivity);

    request.setData(bundle);

    try {
        requestMessenger.send(request);
    } catch (RemoteException ex) {
        ex.printStackTrace();
    }
}
 
Example 14
Project: MyBP   File: RateApp.java   Source Code and License 6 votes vote down vote up
public void appLaunched(Context context) {
    SharedPreferences preferences = context.getSharedPreferences("MyBPreferences", Context.MODE_PRIVATE);
    if(preferences.getBoolean("disabled", false)) {
        return;
    }

    SharedPreferences.Editor editor = preferences.edit();

    long launchCount = preferences.getLong("launchCount", 0) + 1;
    editor.putLong("launchCount", launchCount);

    long firstLaunchDate = preferences.getLong("firstLaunchDate", 0);
    if(firstLaunchDate == 0) {
        firstLaunchDate = System.currentTimeMillis();
        editor.putLong("firstLaunchDate", firstLaunchDate);
    }

    if(launchCount >= LAUNCHES_UNTIL_PROMPT) {
        if(System.currentTimeMillis() >= firstLaunchDate + (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
            showRateDialog(context, editor);
        }
    }

    editor.commit();
}
 
Example 15
Project: airgram   File: ApplicationLoader.java   Source Code and License 5 votes vote down vote up
public static void startPushService() {
    SharedPreferences preferences = applicationContext.getSharedPreferences("Notifications", MODE_PRIVATE);

    if (preferences.getBoolean("pushService", true)) {
        applicationContext.startService(new Intent(applicationContext, NotificationsService.class));
    } else {
        stopPushService();
    }
}
 
Example 16
Project: underlx   File: PairManager.java   Source Code and License 5 votes vote down vote up
public void unpair() {
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString(PREF_API_KEY, "");
    editor.putString(PREF_API_SECRET, "");
    editor.putLong(PREF_API_ACTIVATION, Long.MAX_VALUE);
    editor.commit();
}
 
Example 17
Project: Checkerboard-IMU-Comparator   File: SettingsActivity.java   Source Code and License 5 votes vote down vote up
private void restoreSharedPreferences(){
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putInt(getString(R.string.sharedpreferences_necessary_images_number_key), DEFAULT_NECESSARY_IMAGES_NUMBER);
    editor.putInt(getString(R.string.sharedpreferences_checkerboard_width_key), DEFAULT_CHECKERBOARD_WIDTH);
    editor.putInt(getString(R.string.sharedpreferences_checkerboard_height_key), DEFAULT_CHECKERBOARD_HEIGHT);
    editor.apply();
}
 
Example 18
Project: android-dev-challenge   File: SunshinePreferences.java   Source Code and License 5 votes vote down vote up
/**
 * Resets the location coordinates stores in SharedPreferences.
 *
 * @param context Context used to get the SharedPreferences
 */
public static void resetLocationCoordinates(Context context) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sp.edit();

    editor.remove(PREF_COORD_LAT);
    editor.remove(PREF_COORD_LONG);
    editor.apply();
}
 
Example 19
Project: android-metronome   File: Metronome.java   Source Code and License 5 votes vote down vote up
public void clickSetDefault(View btn)
{
    SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor=prefs.edit();
    editor.putInt("default_bpm", npbpm.getValue());
    editor.putInt("default_measure", Integer.parseInt(etMeasure.getText().toString()));
    editor.commit();
}
 
Example 20
Project: 1946   File: GcmPush.java   Source Code and License 5 votes vote down vote up
public static String getStoredPendingLocalAlarm( Context context, int index )
{
	final SharedPreferences prefs = getGcmPreferences( context );
	String keyData = PROP_ALARM_DATA_N + Integer.toString(index);
	String alarmData = prefs.getString(keyData, null );
	return alarmData;
}
 
Example 21
Project: AndroidMuseumBleManager   File: PreferencesUtils.java   Source Code and License 5 votes vote down vote up
/**
 * get int preferences
 *
 * @param context
 * @param key          The name of the preference to retrieve
 * @param defaultValue Value to return if this preference does not exist
 * @return The preference value if it exists, or defValue. Throws ClassCastException if there is a preference with
 * this name that is not a int
 */
public static int getInt(Context context, String key, int defaultValue) {
    try {
        SharedPreferences settings = context.getSharedPreferences(PREFERENCE_NAME, Context.MODE_PRIVATE);
        return settings.getInt(key, defaultValue);
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return defaultValue;
}
 
Example 22
Project: letv   File: ServerSetting.java   Source Code and License 5 votes vote down vote up
public void setEnvironment(Context context, int i) {
    if (context != null && (this.c == null || this.c.get() == null)) {
        this.c = new WeakReference(context.getSharedPreferences("ServerPrefs", 0));
    }
    if (i == 0 || i == 1) {
        Editor edit;
        switch (i) {
            case 0:
                edit = ((SharedPreferences) this.c.get()).edit();
                edit.putInt("ServerType", 0);
                edit.putString(KEY_OPEN_ENV, "formal");
                edit.putString(KEY_HOST_QZS_QQ, KEY_HOST_QZS_QQ);
                edit.putString(KEY_HOST_OPEN_MOBILE, KEY_HOST_OPEN_MOBILE);
                edit.commit();
                changeServer();
                Toast.makeText(context, "已切换到正式环境", 0).show();
                return;
            case 1:
                edit = ((SharedPreferences) this.c.get()).edit();
                edit.putInt("ServerType", 1);
                edit.putString(KEY_OPEN_ENV, "exp");
                edit.putString(KEY_HOST_QZS_QQ, "testmobile.qq.com");
                edit.putString(KEY_HOST_OPEN_MOBILE, "test.openmobile.qq.com");
                edit.commit();
                changeServer();
                Toast.makeText(context, "已切换到体验环境", 0).show();
                return;
            default:
                return;
        }
    }
    f.e(a, "切换环境参数错误,正式环境为0,体验环境为1");
}
 
Example 23
Project: Options   File: SharedPreferencesStringDropdownOption.java   Source Code and License 5 votes vote down vote up
private SharedPreferencesStringDropdownOption(SharedPreferences sharedPreferences, String key,
                                              String defaultValue, String title,
                                              List<Selection<String>> values) {
    mSharedPreferences = sharedPreferences;
    mKey = key;
    mDefaultValue = defaultValue;
    mTitle = title;
    mValues = values;
}
 
Example 24
Project: simple-keyboard   File: Settings.java   Source Code and License 5 votes vote down vote up
public static boolean readKeyPreviewPopupEnabled(final SharedPreferences prefs,
        final Resources res) {
    final boolean defaultKeyPreviewPopup = res.getBoolean(
            R.bool.config_default_key_preview_popup);
    if (!readFromBuildConfigIfToShowKeyPreviewPopupOption(res)) {
        return defaultKeyPreviewPopup;
    }
    return prefs.getBoolean(PREF_POPUP_ON, defaultKeyPreviewPopup);
}
 
Example 25
Project: DAPNETApp   File: PostCallActivity.java   Source Code and License 5 votes vote down vote up
private void saveData(TransmitterGroupResource[] input){
    SharedPreferences sharedPref = getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = sharedPref.edit();
    Gson gson = new Gson();
    String json = gson.toJson(input);
    prefsEditor.putString("transmitters", json);
    prefsEditor.apply();
}
 
Example 26
Project: Pocket-Plays-for-Twitch   File: Settings.java   Source Code and License 5 votes vote down vote up
/**
 * Chat - Should the chat be able to be showed in landspace
 * @param enableChat True if yes, false if no.
 */

public void setShowChatInLandscape(boolean enableChat) {
	SharedPreferences.Editor editor = getEditor();
	editor.putBoolean(this.CHAT_LANDSCAPE_SWIPABLE, enableChat);
	editor.commit();
}
 
Example 27
Project: ultrasonic   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void loadSettings()
{
	PreferenceManager.setDefaultValues(this, R.xml.settings, false);
	final SharedPreferences preferences = Util.getPreferences(this);

	if (!preferences.contains(Constants.PREFERENCES_KEY_CACHE_LOCATION))
	{
		final SharedPreferences.Editor editor = preferences.edit();
		editor.putString(Constants.PREFERENCES_KEY_CACHE_LOCATION, FileUtil.getDefaultMusicDirectory().getPath());
		editor.commit();
	}
}
 
Example 28
Project: android-dev-challenge   File: SunshinePreferences.java   Source Code and License 5 votes vote down vote up
/**
 * Saves the time that a notification is shown. This will be used to get the ellapsed time
 * since a notification was shown.
 *
 * @param context Used to access SharedPreferences
 * @param timeOfNotification Time of last notification to save (in UNIX time)
 */
public static void saveLastNotificationTime(Context context, long timeOfNotification) {
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sp.edit();
    String lastNotificationKey = context.getString(R.string.pref_last_notification);
    editor.putLong(lastNotificationKey, timeOfNotification);
    editor.apply();
}
 
Example 29
Project: aos-MediaLib   File: Trakt.java   Source Code and License 5 votes vote down vote up
public static void setLoginPreferences(SharedPreferences pref, String user, String sha1) {
    Editor editor = pref.edit();
    if (user != null && sha1 != null) {
        editor.putString(KEY_TRAKT_USER, user);
        editor.putString(KEY_TRAKT_SHA1, sha1);
    } else {
        editor.remove(KEY_TRAKT_USER);
        editor.remove(KEY_TRAKT_SHA1);
    }
    editor.commit();
}
 
Example 30
Project: airgram   File: EmojiView.java   Source Code and License 5 votes vote down vote up
private void saveRecentStickers() {
    SharedPreferences.Editor editor = getContext().getSharedPreferences("emoji", Activity.MODE_PRIVATE).edit();
    StringBuilder stringBuilder = new StringBuilder();
    for (int a = 0; a < newRecentStickers.size(); a++) {
        if (stringBuilder.length() != 0) {
            stringBuilder.append(",");
        }
        stringBuilder.append(newRecentStickers.get(a));
    }
    editor.putString("stickers2", stringBuilder.toString());
    editor.commit();
}
 
Example 31
Project: Say_it   File: UtilitySharedPrefs.java   Source Code and License 5 votes vote down vote up
public static void savePrefs(Context context, int value, String prefs_key) {
    SharedPreferences settings = context.getSharedPreferences(MainActivity.PREFS_NAME, MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    editor.putInt(prefs_key, value);
    editor.apply();
}
 
Example 32
Project: MeetMusic   File: MyMusicUtil.java   Source Code and License 5 votes vote down vote up
public static void setNightMode(Context context, boolean mode) {
    if (mode) {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
    } else {
        AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
    }
    SharedPreferences sharedPreferences = context.getSharedPreferences(Constant.THEME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor =  sharedPreferences.edit();
    editor.putBoolean("night", mode).commit();
}
 
Example 33
Project: mousetodon   File: MouseApp.java   Source Code and License 5 votes vote down vote up
void addAccount() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            // show the window where the user must enter his credentials
            UserInput.show(main, new NextAction() {
                public void run(String res) {
                    String[] ss = res.split(" ");
                    if (ss.length>2) {
                        useremail=ss[0];
                        userpwd=ss[1];
                        instanceDomain=ss[2];
                        if (useremail.length()==0 || userpwd.length()==0 || instanceDomain.length()==0)
                            message("All 3 fields are mandatory");
                        else {
                            SharedPreferences.Editor edit = pref.edit();
                            MouseApp.main.allinstances.add(instanceDomain);
                            String s = "";
                            for (String iss: MouseApp.main.allinstances) s+=iss+" ";
                            s=s.trim();
                            edit.putString("mouseapp_insts", s);
                            edit.putString(String.format("user_for_%s", instanceDomain), useremail);
                            edit.putString(String.format("pswd_for_%s", instanceDomain), userpwd);
                            edit.commit();
                            setInstanceSpinner();
                            serverStage1();
                        }
                    }
                }
            });
        }
    });
}
 
Example 34
Project: hyperrail-for-android   File: PersistentQueryProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Remove a query from a tag
 *
 * @param tag   The tag to remove from
 * @param query The query to remove
 */
private void remove(String tag, Suggestable query) {
    Set<String> items = new HashSet<>(sharedPreferences.getStringSet(tag, new HashSet<String>()));

    // If this query is already in the recents list, remove it (so we can update it)
    items = removeFromPersistentSet(items, query);

    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putStringSet(tag, items);
    editor.apply();
}
 
Example 35
Project: SilicaGel   File: TwitterUtil.java   Source Code and License 5 votes vote down vote up
private static AccessToken loadAccessToken(Context context) {
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
    String token = pref.getString("twitter_token", null);
    String tokenSecret = pref.getString("twitter_secret", null);
    
    if (token != null && tokenSecret != null) {
        return new AccessToken(token, tokenSecret);
    } else {
        return null;
    }
}
 
Example 36
Project: oma-riista-android   File: GameDatabase.java   Source Code and License 5 votes vote down vote up
public SyncMode getSyncMode(Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    if (prefs.contains(syncModeKey)) {
        int syncMode = prefs.getInt(syncModeKey, 0);
        if (SyncMode.values().length > syncMode) {
            return SyncMode.values()[syncMode];
        }
    }
    return SyncMode.SYNC_AUTOMATIC;
}
 
Example 37
Project: a_whattobuy   File: SettingsService.java   Source Code and License 5 votes vote down vote up
public void loadSettings(Activity c) {
    SharedPreferences sp = c.getPreferences(Context.MODE_PRIVATE);

    Map<String, ?> all = sp.getAll();

    for (Map.Entry<String, ?> e : all.entrySet()) {
        settings.put(e.getKey(), e.getValue());
    }
}
 
Example 38
Project: ESSocialSDK-master   File: AccessTokenKeeper.java   Source Code and License 5 votes vote down vote up
/**
 * 保存 Token 对象到 SharedPreferences。
 *
 * @param context 应用程序上下文环境
 * @param token   Token 对象
 */
public static void writeAccessToken(Context context, Oauth2AccessToken token) {
    if (null == context || null == token) {
        return;
    }

    SharedPreferences pref = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_APPEND);
    Editor editor = pref.edit();
    editor.putString(KEY_UID, token.getUid());
    editor.putString(KEY_ACCESS_TOKEN, token.getToken());
    editor.putString(KEY_REFRESH_TOKEN, token.getRefreshToken());
    editor.putLong(KEY_EXPIRES_IN, token.getExpiresTime());
    editor.commit();
}
 
Example 39
Project: PlusGram   File: NotificationsController.java   Source Code and License 5 votes vote down vote up
public void cleanup() {
    popupMessages.clear();
    popupReplyMessages.clear();
    notificationsQueue.postRunnable(new Runnable() {
        @Override
        public void run() {
            opened_dialog_id = 0;
            total_unread_count = 0;
            personal_count = 0;
            pushMessages.clear();
            pushMessagesDict.clear();
            pushDialogs.clear();
            wearNotificationsIds.clear();
            delayedPushMessages.clear();
            notifyCheck = false;
            lastBadgeCount = 0;
            try {
                if (notificationDelayWakelock.isHeld()) {
                    notificationDelayWakelock.release();
                }
            } catch (Exception e) {
                FileLog.e("tmessages", e);
            }
            setBadge(0);
            SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.commit();
        }
    });
}
 
Example 40
Project: material-two-stage-rating   File: PrefUtils.java   Source Code and License 5 votes vote down vote up
public static void setIntSystemValue(final String key, final int value, final Context context) {
    SharedPreferences myPrefs = context
            .getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putInt(key, value);
    prefsEditor.commit();
}
 
Example 41
Project: Hexpert   File: GameHelper.java   Source Code and License 5 votes vote down vote up
int incrementSignInCancellations() {
    int cancellations = getSignInCancellations();
    SharedPreferences.Editor editor = mAppContext.getSharedPreferences(
            GAMEHELPER_SHARED_PREFS, Context.MODE_PRIVATE).edit();
    editor.putInt(KEY_SIGN_IN_CANCELLATIONS, cancellations + 1);
    editor.commit();
    return cancellations + 1;
}
 
Example 42
Project: TaBeTa   File: LevelChooseAdapter.java   Source Code and License 5 votes vote down vote up
public LevelChooseAdapter(LevelChose mainActivity,
		SharedPreferences information, int WorldNum) {
	// TODO Auto-generated constructor stub
	// result=prgmNameList;
	context = mainActivity;
	this.information = information;
	// imageId=prgmImages;

	WorldNumber = WorldNum;

}
 
Example 43
Project: android-ponewheel   File: MainActivity.java   Source Code and License 5 votes vote down vote up
@Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        Log.i(TAG, "onSharedPreferenceChanged callback");
        switch (key) {
            case SharedPreferencesUtil.METRIC_UNITS:
                mOWDevice.refreshCharacteristics();
                refreshMetricViews();
                break;

            case SharedPreferencesUtil.DARK_NIGHT_MODE:
                boolean checkDarkNightMode = sharedPreferences.getBoolean(key, false);
                getDelegate().setLocalNightMode(
                        checkDarkNightMode ?
                                AppCompatDelegate.MODE_NIGHT_YES
                                : AppCompatDelegate.MODE_NIGHT_NO);

                recreate();
//                mTracker.send(new HitBuilders.EventBuilder().setCategory("SharedPreferences").setAction("darkNightMode")
//                        .setLabel((checkDarkNightMode) ? "on" : "off").build());
                break;

            case SharedPreferencesUtil.LOG_LOCATIONS:
                boolean checkLogLocations = sharedPreferences.getBoolean(key, false);
                if (!checkLogLocations && mOWDevice != null) {
                    mOWDevice.setGpsLocation(null);
                }
                break;

            default:
                Log.d(TAG, "onSharedPreferenceChanged: " + key);
        }

    }
 
Example 44
Project: AndroidBackendlessChat   File: AuthorizationClient.java   Source Code and License 5 votes vote down vote up
private void saveCookieToken(String token) {
    Context context = getStartActivityDelegate().getActivityContext();
    SharedPreferences sharedPreferences = context.getSharedPreferences(
            WEB_VIEW_AUTH_HANDLER_STORE,
            Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(WEB_VIEW_AUTH_HANDLER_TOKEN_KEY, token);
    if (!editor.commit()) {
        Utility.logd(TAG, "Could not update saved web view auth handler token.");
    }
}
 
Example 45
Project: react-native-leancloud-sdk   File: RNPushNotificationHelper.java   Source Code and License 5 votes vote down vote up
private static void commit(SharedPreferences.Editor editor) {
    if (Build.VERSION.SDK_INT < 9) {
        editor.commit();
    } else {
        editor.apply();
    }
}
 
Example 46
Project: buildAPKsSamples   File: VoiceRecognitionService.java   Source Code and License 5 votes vote down vote up
@Override
protected void onStartListening(Intent recognizerIntent, Callback listener) {
    // A real recognizer would probably utilize a lot of the other listener callback
    // methods. But we'll just skip all that and pretend we've got a result.
    ArrayList<String> results = new ArrayList<String>();
    
    SharedPreferences prefs = getSharedPreferences(
            VoiceRecognitionSettings.SHARED_PREFERENCES_NAME,
            Context.MODE_PRIVATE);
    
    String resultType = prefs.getString(
            VoiceRecognitionSettings.PREF_KEY_RESULTS_TYPE,
            String.valueOf(VoiceRecognitionSettings.RESULT_TYPE_LETTERS));
    int resultTypeInt = Integer.parseInt(resultType);
    
    if (resultTypeInt == VoiceRecognitionSettings.RESULT_TYPE_LETTERS) {
        results.add("a");
        results.add("b");
        results.add("c");            
    } else if (resultTypeInt == VoiceRecognitionSettings.RESULT_TYPE_NUMBERS) {
        results.add("1");
        results.add("2");
        results.add("3");
    }
    
    Bundle bundle = new Bundle();
    bundle.putStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION, results);
    
    try {
        listener.results(bundle);
    } catch (RemoteException e) {
        throw new RuntimeException(e);
    }
}
 
Example 47
Project: Raffler-Android   File: AppManager.java   Source Code and License 5 votes vote down vote up
/**
 * get user data from local storage
 * @return user
 */
public static User getSession() {
    Context context = AppManager.getInstance().context;
    SharedPreferences sharedPreferences = context.getSharedPreferences("AppSession", Context.MODE_PRIVATE);
    String uid = sharedPreferences.getString("uid", null);
    String name = sharedPreferences.getString("name", "?");
    String photo = sharedPreferences.getString("photo", "?");
    String phone = sharedPreferences.getString("phone", "");
    String bio = sharedPreferences.getString("bio", "?");
    String pushToken = sharedPreferences.getString("pushToken", "?");
    int userStatus = sharedPreferences.getInt("userStatus", 0);
    int userAction = sharedPreferences.getInt("userAction", 0);
    int raffle_point = sharedPreferences.getInt("raffle_point", 0);
    String chatsDic = sharedPreferences.getString("chats", null);
    Map<String,Object> chats = new Gson().fromJson(chatsDic, new TypeToken<Map<String, Object>>(){}.getType());
    String lastSeenDic = sharedPreferences.getString("lastseens", null);
    Map<String,Object> lastSeens = new Gson().fromJson(lastSeenDic, new TypeToken<Map<String, Object>>(){}.getType());
    String rafflesDic = sharedPreferences.getString("raffles", null);
    Map<String,Object> raffles = new Gson().fromJson(rafflesDic, new TypeToken<Map<String, Object>>(){}.getType());
    if (uid != null) {
        Map<String, Object> data = new HashMap<>();
        data.put("uid", uid);
        data.put("name", name);
        data.put("photo", photo);
        data.put("phone", phone);
        data.put("bio", bio);
        data.put("pushToken", pushToken);
        data.put("userStatus", userStatus);
        data.put("userAction", userAction);
        data.put("chats", (chats != null) ? chats : new HashMap<String, Object>());
        data.put("lastseens", (lastSeens != null) ? lastSeens : new HashMap<String, Object>());
        data.put("raffles", (raffles != null) ? raffles : new HashMap<String, Object>());
        data.put("raffle_point", raffle_point);
        User user = new User(data);
        return user;
    } else {
        return null;
    }
}
 
Example 48
Project: smart-lens   File: SharedPrefsProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Save value to shared preference
 *
 * @param key   key of preference field
 * @param value value to store
 */
public void savePreferences(@NonNull String key, boolean value) {
    //Save to share prefs
    SharedPreferences.Editor prefsEditor = mSharedPreference.edit();
    prefsEditor.putBoolean(key, value);
    prefsEditor.apply();
}
 
Example 49
Project: PlusGram   File: ChangeAboutActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onResume() {
    super.onResume();
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
    boolean animations = preferences.getBoolean("view_animations", true);
    if (!animations) {
        aboutField.requestFocus();
        AndroidUtilities.showKeyboard(aboutField);
    }
    updateTheme();
}
 
Example 50
Project: CustomAndroidOneSheeld   File: FoursquareShield.java   Source Code and License 5 votes vote down vote up
public void jsonParser(String result) {
    try {
        JSONObject json = new JSONObject(result);
        JSONObject response = json.getJSONObject("response");
        JSONObject user = response.getJSONObject("user");
        String userName = user.getString("firstName");
        // Set user name UI
        if (eventHandler != null)
            eventHandler.onForsquareLoggedIn(userName);
        JSONObject venue = user.getJSONObject("checkins")
                .getJSONArray("items").getJSONObject(0)
                .getJSONObject("venue");
        String placeName = venue.getString("name");
        if (eventHandler != null)
            eventHandler.onPlaceCheckin(placeName);

        // save in share prefrences
        SharedPreferences.Editor editor = mSharedPreferences.edit();
        editor.putString("PREF_FourSquare_UserName", userName);
        editor.putString("PREF_FourSquare_LastPlace", placeName);

        // Commit the edits!
        editor.commit();

    } catch (JSONException e) {
        // TODO Auto-generated catch block
        Log.e("TAG", "Foursquare::jsonParser", e);
    }

}
 
Example 51
Project: AndroidBlueprints   File: ApplicationModule.java   Source Code and License 4 votes vote down vote up
@Provides
@Singleton
PreferencesService providesPreferencesService(SharedPreferences sharedPreferences) {
    return new PreferencesService(sharedPreferences);
}
 
Example 52
Project: financisto1-holo   File: MyPreferences.java   Source Code and License 4 votes vote down vote up
public static boolean isShowIsCCardPayment(Context context) {
	SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
	return sharedPreferences.getBoolean("ntsl_show_is_ccard_payment", true);
}
 
Example 53
Project: ultrasonic   File: Util.java   Source Code and License 4 votes vote down vote up
public static boolean shouldDisplayBitrateWithArtist(Context context)
{
	SharedPreferences preferences = getPreferences(context);
	return preferences.getBoolean(Constants.PREFERENCES_KEY_DISPLAY_BITRATE_WITH_ARTIST, true);
}
 
Example 54
Project: ultrasonic   File: Util.java   Source Code and License 4 votes vote down vote up
private static boolean isWifiRequiredForDownload(Context context)
{
	SharedPreferences preferences = getPreferences(context);
	return preferences.getBoolean(Constants.PREFERENCES_KEY_WIFI_REQUIRED_FOR_DOWNLOAD, false);
}
 
Example 55
Project: GSB-2017-Android   File: PrefUtils.java   Source Code and License 4 votes vote down vote up
public static boolean getBoolean(Context context, int key, boolean defValue) {
    SharedPreferences
            pref = PreferenceManager
            .getDefaultSharedPreferences(context);
    return pref.getBoolean(context.getString(key), defValue);
}
 
Example 56
Project: FuelFriend   File: PreferenceHelper.java   Source Code and License 4 votes vote down vote up
private static SharedPreferences.Editor getEditor(Context context) {
    SharedPreferences preferences = getSharedPreferences(context);
    return preferences.edit();
}
 
Example 57
Project: buildAPKsSamples   File: CubeWallpaper2Settings.java   Source Code and License 4 votes vote down vote up
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
        String key) {
}
 
Example 58
Project: mvo   File: SettingsFragment.java   Source Code and License 4 votes vote down vote up
private boolean isEnabledVolumeKeyFix(){
    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity());
    return pref.getBoolean("volume_key_lock", false);
}
 
Example 59
Project: FastReading   File: BookInfo.java   Source Code and License 4 votes vote down vote up
public SharedPreferences getBookSpeedsPreferences() {
    return bookSpeedsPreferences;
}
 
Example 60
Project: airgram   File: LoginActivity.java   Source Code and License 4 votes vote down vote up
private void clearCurrentState() {
    SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("logininfo2", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.commit();
}