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:fr.cph.chicago.activity.BaseActivity.java

/**
 * Connect to CTA API and get arrivals trains and buses from favorites
 * /* w ww.ja  v a  2s.c o m*/
 * @throws ParserException
 *             the exception
 */
private void loadData() throws ParserException {
    MultiMap<String, String> params = new MultiValueMap<String, String>();
    List<Integer> favorites = Preferences.getTrainFavorites(ChicagoTracker.PREFERENCE_FAVORITES_TRAIN);
    for (Integer fav : favorites) {
        params.put("mapid", String.valueOf(fav));
    }

    MultiMap<String, String> params2 = new MultiValueMap<String, String>();
    List<String> busFavorites = Preferences.getBusFavorites(ChicagoTracker.PREFERENCE_FAVORITES_BUS);
    for (String str : busFavorites) {
        String[] fav = Util.decodeBusFavorite(str);
        params2.put("rt", fav[0]);
        params2.put("stpid", fav[1]);
    }

    // Get preferences to know if trains and buses need to be loaded
    SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    boolean loadTrain = true;
    boolean loadBus = true;
    if (sharedPref.contains("cta_train")) {
        loadTrain = sharedPref.getBoolean("cta_train", true);
    } else {
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("cta_train", true);
        editor.commit();
    }
    if (sharedPref.contains("cta_bus")) {
        loadBus = sharedPref.getBoolean("cta_bus", true);
    } else {
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("cta_bus", true);
        editor.commit();
    }

    GlobalConnectTask task = new GlobalConnectTask(this, BaseActivity.class, CtaRequestType.TRAIN_ARRIVALS,
            params, CtaRequestType.BUS_ARRIVALS, params2, loadTrain, loadBus, false);
    task.execute((Void) null);
    if (loadTrain) {
        Util.trackAction(BaseActivity.this, R.string.analytics_category_req,
                R.string.analytics_action_get_train, R.string.analytics_action_get_train_arrivals, 0);
    }
    if (loadBus) {
        Util.trackAction(BaseActivity.this, R.string.analytics_category_req, R.string.analytics_action_get_bus,
                R.string.analytics_action_get_bus_arrival, 0);
    }
}

From source file:com.cs442.group5.feedback.DashBoardActivity.java

@Override
protected void onResume() {
    super.onResume();
    Log.e(TAG, "onResume: ");
    final SharedPreferences sf = getSharedPreferences("dashboard", MODE_PRIVATE);
    if (sf.contains("myStores")) {

        myStores.clear();//w ww.j  a v  a  2 s  .  c  o m
        Log.e(TAG, "run: ");
        myStores = new Gson().fromJson(sf.getString("myStores", ""), new TypeToken<ArrayList<Store>>() {
        }.getType());
        if (myStores.size() > 0) {
            arrayAdapter = new MyStoreDashboardArrayAdapter(context, myStores);
            gridview_myStores.setAdapter(arrayAdapter);
            arrayAdapter.notifyDataSetChanged();
        } else
            getAllStores();

    } else {
        Log.e(TAG, "onResume: getting all stores");

        getAllStores();

    }

}

From source file:org.openhab.habdroid.ui.OpenHABStartupActivity.java

@Override
public void onServiceResolved(ServiceInfo serviceInfo) {
    Log.i(TAG, "Service resolved: " + serviceInfo.getHostAddresses()[0] + " port:" + serviceInfo.getPort());
    openHABBaseUrl = "https://" + serviceInfo.getHostAddresses()[0] + ":"
            + String.valueOf(serviceInfo.getPort()) + "/";
    progressDialog.hide();/*from w  w w. ja  va 2  s.c o  m*/
    AsyncHttpClient asyncHttpClient = new MyAsyncHttpClient();
    asyncHttpClient.get(openHABBaseUrl + "static/uuid", new AsyncHttpResponseHandler() {

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
            Toast.makeText(getApplicationContext(), "@string/error_no_uuid", Toast.LENGTH_LONG).show();

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] response) {
            // TODO Auto-generated method stub
            final String content = new String(response);
            // TODO Auto-generated method stub
            Log.i(TAG, "Got openHAB UUID = " + content);
            SharedPreferences settings = PreferenceManager
                    .getDefaultSharedPreferences(OpenHABStartupActivity.this);
            if (settings.contains("openhab_uuid")) {
                String openHABUUID = settings.getString("openhab_uuid", "");
                if (openHABUUID.equals(content)) {
                    Log.i(TAG, "openHAB UUID does match the saved one");
                    startListActivity(openHABBaseUrl);
                } else {
                    Log.i(TAG, "openHAB UUID doesn't match the saved one");
                    // TODO: need to add some user prompt here
                    /*                  Toast.makeText(getApplicationContext(), 
                                            "openHAB UUID doesn't match the saved one!",
                                            Toast.LENGTH_LONG).show();*/
                    startListActivity(openHABBaseUrl);
                }
            } else {
                Log.i(TAG, "No recorded openHAB UUID, saving the new one");
                Editor preferencesEditor = settings.edit();
                preferencesEditor.putString("openhab_uuid", content);
                preferencesEditor.commit();
                startListActivity(openHABBaseUrl);
            }
        }

    });
}

From source file:org.lumicall.android.sip.RegisterOtherAccount.java

protected void doOtherAccountSetup() throws Exception {
    buttonDone.setEnabled(false);//from   ww  w.j  a  v  a2 s .  c  o m

    AppProperties props = new AppProperties(this);

    if (accountField == null) {
        Log.e(TAG, "accountField == null");
    }
    if (passwordField == null) {
        Log.e(TAG, "passwordField == null");
    }

    String sIPAccountId = accountField.getText().toString();
    String password = passwordField.getText().toString();

    SIPIdentity sipIdentity = new SIPIdentity();
    sipIdentity.setUri(sIPAccountId);
    sipIdentity.setAuthUser(sIPAccountId); // do HA1b by default
    sipIdentity.setAuthPassword(password);
    sipIdentity.setReg(true);
    //sipIdentity.setRegServerName(props.getSipServer());
    sipIdentity.setRegServerName("");
    sipIdentity.setRegServerPort(props.getSipPort());
    sipIdentity.setRegServerProtocol(props.getSipProtocol());
    //sipIdentity.setOutboundServerName(props.getSipServer());
    sipIdentity.setOutboundServerName("");
    sipIdentity.setOutboundServerPort(props.getSipPort());
    sipIdentity.setOutboundServerProtocol(props.getSipProtocol());
    sipIdentity.setCarrierRoute(false); // FIXME - offer a checkbox for this?
    //sipIdentity.setStunServerName(props.getStunServer());
    sipIdentity.setStunServerName("");
    sipIdentity.setStunServerPort(props.getStunPort());
    sipIdentity.setStunServerProtocol("udp");

    LumicallDataSource ds = new LumicallDataSource(this);
    ds.open();
    for (SIPIdentity s : ds.getSIPIdentities()) {
        if (s.getUri().equals(sipIdentity.getUri()))
            sipIdentity.setId(s.getId());
    }
    ds.persistSIPIdentity(sipIdentity);
    ds.close();
    Log.v(TAG, "Configured account: " + sIPAccountId);

    SharedPreferences sipSettings = getSharedPreferences(Settings.sharedPrefsFile, Context.MODE_PRIVATE);
    if (!sipSettings.contains(Settings.PREF_SIP)) {
        Editor edSIP = sipSettings.edit();
        edSIP.putString(Settings.PREF_SIP, Long.toString(sipIdentity.getId()));
        if (!sipSettings.contains(Settings.PREF_TEL))
            edSIP.putString(Settings.PREF_TEL, "-1");

        /* edSIP.putString(Settings.PREF_USERNAME, settings.getString(RegisterAccount.PREF_PHONE_NUMBER, null));
        edSIP.putString(Settings.PREF_PASSWORD, settings.getString(RegisterAccount.PREF_SECRET, null));
        edSIP.putString(Settings.PREF_SERVER, DEFAULT_SIP_SERVER);
        edSIP.putString(Settings.PREF_DOMAIN, DEFAULT_SIP_DOMAIN);
        edSIP.putString(Settings.PREF_PROTOCOL, "tcp");  // FIXME - change to TLS
        edSIP.putBoolean(Settings.PREF_STUN, true);
        edSIP.putString(Settings.PREF_STUN_SERVER, DEFAULT_STUN_SERVER);
        edSIP.putString(Settings.PREF_STUN_SERVER_PORT, "" + DEFAULT_STUN_SERVER_PORT); */
        edSIP.putBoolean(Settings.PREF_WLAN, true);
        edSIP.putBoolean(Settings.PREF_EDGE, true);
        edSIP.putBoolean(Settings.PREF_3G, true);
        edSIP.putBoolean(Settings.PREF_ON, true);

        if (edSIP.commit())
            Log.v(TAG, "Configured prefs");
        else {
            Log.e(TAG, "error while committing preferences");
        }
    }

    //Receiver.engine(this).updateDNS();
    Receiver.engine(this).halt();
    Receiver.engine(this).StartEngine();

    doMainActivity();
}

From source file:ly.count.android.api.CountlyStoreTests.java

public void testClear() {
    final SharedPreferences prefs = getContext().getSharedPreferences("COUNTLY_STORE", Context.MODE_PRIVATE);
    assertFalse(prefs.contains("EVENTS"));
    assertFalse(prefs.contains("CONNECTIONS"));
    store.addConnection("blah");
    store.addEvent("eventKey", null, Countly.currentTimestamp(), 1, 0.0d);
    assertTrue(prefs.contains("EVENTS"));
    assertTrue(prefs.contains("CONNECTIONS"));
    store.clear();/*from   ww  w  .j  av  a 2  s  .  c o m*/
    assertFalse(prefs.contains("EVENTS"));
    assertFalse(prefs.contains("CONNECTIONS"));
}

From source file:org.dpadgett.timer.TimerActivity.java

/** Called when the activity is first created. */
@Override/*from   w  w w .j  a  v a  2s . c o m*/
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final ViewPager mViewPager = new ViewPager(this);
    mViewPager.setId(R.id.viewPager);
    mViewPager.setOffscreenPageLimit(Tab.values().length);
    setContentView(mViewPager);

    final ActionBar bar = getSupportActionBar();
    bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
    bar.setDisplayShowHomeEnabled(false);

    final Bundle extras = getIntent().getExtras();

    mTabsAdapter = new TabsAdapter(this, mViewPager);
    final Context context = getApplicationContext();
    for (final Tab tab : Tab.values()) {
        final String tabTitle = context.getString(tab.getTitle());
        mTabsAdapter.addTab(bar.newTab().setText(tabTitle), tab.getFragmentClass(), extras);
    }

    StartReason startReason = StartReason.START_REASON_NONE;
    if (extras != null) {
        startReason = (StartReason) extras.getSerializable(START_REASON);
    }

    final SharedPreferences prefs = getSharedPreferences("TimerActivity", Context.MODE_PRIVATE);
    if (startReason == StartReason.START_REASON_AUTOSTART_STOPWATCH) {
        bar.setSelectedNavigationItem(Tab.STOPWATCH.ordinal());
    } else if (prefs.contains("tab")) {
        bar.setSelectedNavigationItem(prefs.getInt("tab", 0));
    } else if (savedInstanceState != null) {
        bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
    }

    alarmDialog = new AlertDialog.Builder(this).setTitle(context.getString(R.string.countdown_timer_finished))
            .setPositiveButton(context.getString(R.string.alarm_dialog_dismiss),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(final DialogInterface dialog, final int which) {
                            dialog.dismiss();
                            final Intent intent = new Intent(TimerActivity.this, AlarmService.class)
                                    .putExtra("startAlarm", false).putExtra("fromFragment", true)
                                    .setAction("stopAlarm");
                            TimerActivity.this.startService(intent);
                        }
                    })
            .setCancelable(false).create();

    if (prefs.getBoolean("countdownDialogShowing", false)) {
        alarmDialog.show();
    }

    getApplicationContext().registerReceiver(showDialogReceiver, new IntentFilter(ACTION_SHOW_DIALOG));
    getApplicationContext().registerReceiver(dismissDialogReceiver, new IntentFilter(ACTION_DISMISS_DIALOG));
}

From source file:org.rebo.app.MapLayers.java

void setPreferences(Context context) {
    setBaseMap(context);//from   www. j av  a  2  s.  c  o  m

    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

    ThemeFile theme = VtmThemes.DEFAULT;
    if (preferences.contains("theme")) {
        String name = preferences.getString("theme", "DEFAULT");
        try {
            theme = VtmThemes.valueOf(name);
        } catch (IllegalArgumentException e) {
            theme = VtmThemes.DEFAULT;
        }
    }

    App.map.setTheme(theme);

    // default cache size 20MB
    int cacheSize = preferences.getInt("cacheSize", 20);

    if (mCache != null)
        mCache.setCacheSize(cacheSize * (1 << 20));

}

From source file:im.vector.VectorApp.java

/**
 * Provides the current application locale
 *
 * @return the application locale/* w  w w.j  a v  a  2  s .c  om*/
 */
public static Locale getApplicationLocale() {
    Context context = VectorApp.getInstance();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    Locale locale;

    if (!preferences.contains(APPLICATION_LOCALE_LANGUAGE_KEY)) {
        locale = Locale.getDefault();

        // detect if the default language is used
        String defaultStringValue = getString(context, mApplicationDefaultLanguage, R.string.resouces_country);
        if (TextUtils.equals(defaultStringValue, getString(context, locale, R.string.resouces_country))) {
            locale = mApplicationDefaultLanguage;
        }

        saveApplicationLocale(locale);
    } else {
        locale = new Locale(preferences.getString(APPLICATION_LOCALE_LANGUAGE_KEY, ""),
                preferences.getString(APPLICATION_LOCALE_COUNTRY_KEY, ""),
                preferences.getString(APPLICATION_LOCALE_VARIANT_KEY, ""));
    }

    return locale;
}

From source file:im.vector.VectorApp.java

/**
 * Get the font scale//from   w w  w .  j ava  2s.  c o  m
 *
 * @return the font scale
 */
public static String getFontScale() {
    Context context = VectorApp.getInstance();
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String scalePreferenceKey;

    if (!preferences.contains(APPLICATION_FONT_SCALE_KEY)) {
        float fontScale = context.getResources().getConfiguration().fontScale;

        scalePreferenceKey = FONT_SCALE_NORMAL;

        if (mPrefKeyByFontScale.containsKey(fontScale)) {
            scalePreferenceKey = mPrefKeyByFontScale.get(fontScale);
        }

        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(APPLICATION_FONT_SCALE_KEY, scalePreferenceKey);
        editor.commit();
    } else {
        scalePreferenceKey = preferences.getString(APPLICATION_FONT_SCALE_KEY, FONT_SCALE_NORMAL);
    }

    return scalePreferenceKey;
}

From source file:org.iisgcp.waterwalk.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    setContentView(R.layout.activity_main);

    mDrawerTitles = getResources().getStringArray(R.array.drawer_items);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.left_drawer);

    // set a custom shadow that overlays the main content when the drawer opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
    // set up the drawer's list view with items and click listener
    mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mDrawerTitles));
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Set up the dropdown list navigation in the action bar.
    actionBar.setListNavigationCallbacks(
            // Specify a SpinnerAdapter to populate the dropdown list.
            new ArrayAdapter<String>(getActionBarThemedContextCompat(),
                    android.R.layout.simple_dropdown_item_1line, android.R.id.text1,
                    new String[] { getString(R.string.title_grid), getString(R.string.title_map) }),
            this);

    LayoutInflater inflator = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflator.inflate(R.layout.actionbar, null);
    actionBar.setCustomView(view);/*from w  w w.  ja v a  2 s. c o m*/

    setTitle(getString(R.string.title_routes));

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
            R.string.drawer_open, /* "open drawer" description for accessibility */
            R.string.drawer_close /* "close drawer" description for accessibility */
    ) {

        public void onDrawerClosed(View view) {
            if (mDrawerList.getCheckedItemPosition() == 0) {
                setTitle(mDrawerTitles[0]);
                getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
            } else {
                setTitle(mDrawerTitles[1]);
                getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
            }
        }

        public void onDrawerOpened(View drawerView) {
            setTitle(getString(R.string.app_name));
            getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    if (savedInstanceState == null) {
        selectItem(0);
    }

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    if (!prefs.contains(Constants.INTENT_DRAWER_POSITION)) {
        mDrawerLayout.closeDrawer(mDrawerList);
        mDrawerLayout.openDrawer(Gravity.LEFT);
        showDialog(HELP_DIALOG);
    }
}