Example usage for android.app Activity getSharedPreferences

List of usage examples for android.app Activity getSharedPreferences

Introduction

In this page you can find the example usage for android.app Activity getSharedPreferences.

Prototype

@Override
    public SharedPreferences getSharedPreferences(String name, int mode) 

Source Link

Usage

From source file:com.example.android.apprestrictionenforcer.AppRestrictionEnforcerFragment.java

/**
 * Loads the restrictions for the AppRestrictionSchema sample.
 *
 * @param activity The activity/*from ww w  .  j  a  v a2  s  .  co  m*/
 */
private void loadRestrictions(Activity activity) {
    RestrictionsManager manager = (RestrictionsManager) activity.getSystemService(Context.RESTRICTIONS_SERVICE);
    List<RestrictionEntry> restrictions = manager
            .getManifestRestrictions(Constants.PACKAGE_NAME_APP_RESTRICTION_SCHEMA);
    SharedPreferences prefs = activity.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE);
    for (RestrictionEntry restriction : restrictions) {
        String key = restriction.getKey();
        if (RESTRICTION_KEY_SAY_HELLO.equals(key)) {
            updateCanSayHello(prefs.getBoolean(RESTRICTION_KEY_SAY_HELLO, restriction.getSelectedState()));
        } else if (RESTRICTION_KEY_MESSAGE.equals(key)) {
            updateMessage(prefs.getString(RESTRICTION_KEY_MESSAGE, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_NUMBER.equals(key)) {
            updateNumber(prefs.getInt(RESTRICTION_KEY_NUMBER, restriction.getIntValue()));
        } else if (RESTRICTION_KEY_RANK.equals(key)) {
            updateRank(activity, restriction.getChoiceValues(),
                    prefs.getString(RESTRICTION_KEY_RANK, restriction.getSelectedString()));
        } else if (RESTRICTION_KEY_APPROVALS.equals(key)) {
            updateApprovals(activity, restriction.getChoiceValues(),
                    TextUtils.split(
                            prefs.getString(RESTRICTION_KEY_APPROVALS,
                                    TextUtils.join(DELIMETER, restriction.getAllSelectedStrings())),
                            DELIMETER));
        } else if (BUNDLE_SUPPORTED && RESTRICTION_KEY_ITEMS.equals(key)) {
            String itemsString = prefs.getString(RESTRICTION_KEY_ITEMS, "");
            HashMap<String, String> items = new HashMap<>();
            for (String itemString : TextUtils.split(itemsString, DELIMETER)) {
                String[] strings = itemString.split(SEPARATOR, 2);
                items.put(strings[0], strings[1]);
            }
            updateItems(activity, items);
        }
    }
}

From source file:com.nikhilnayak.games.octoshootar.ui.fragments.GameScoreFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    mAttachTime = System.currentTimeMillis();
    if (activity instanceof GameScoreFragment.Listener) {
        mListener = (GameScoreFragment.Listener) activity;
        mPlayerProfile = new PlayerProfile(
                activity.getSharedPreferences(PlayerProfile.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE));
    } else {// ww w . j  a  v a2 s  . c om
        throw new ClassCastException(activity.toString() + " must implement GameScoreFragment.Listener");
    }
}

From source file:uk.org.rivernile.edinburghbustracker.android.fragments.general.NearestStopsFragment.java

/**
 * {@inheritDoc}/*from  w w w  . j  av  a2  s .  c  o  m*/
 */
@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final Activity activity = getActivity();
    // Get references to required resources.
    locMan = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
    sp = activity.getSharedPreferences(PreferencesActivity.PREF_FILE, 0);
    bsd = BusStopDatabase.getInstance(activity.getApplicationContext());
    sd = SettingsDatabase.getInstance(activity.getApplicationContext());
    // Create the ArrayAdapter for the ListView.
    ad = new NearestStopsArrayAdapter(activity);

    // Initialise the services chooser Dialog.
    services = bsd.getBusServiceList();

    if (savedInstanceState != null) {
        chosenServices = savedInstanceState.getStringArray(ARG_CHOSEN_SERVICES);
    } else {
        // Check to see if GPS is enabled then check to see if the GPS
        // prompt dialog has been disabled.
        if (!locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)
                && !sp.getBoolean(PreferencesActivity.PREF_DISABLE_GPS_PROMPT, false)) {
            // Get the list of Activities which can handle the enabling of
            // location services.
            final List<ResolveInfo> packages = activity.getPackageManager()
                    .queryIntentActivities(TurnOnGpsDialogFragment.TURN_ON_GPS_INTENT, 0);
            // If the list is not empty, this means Activities do exist.
            // Show Dialog asking users if they want to turn on GPS.
            if (packages != null && !packages.isEmpty()) {
                callbacks.onAskTurnOnGps();
            }
        }
    }

    // Tell the underlying Activity that this Fragment contains an options
    // menu.
    setHasOptionsMenu(true);
}

From source file:com.tinyhydra.botd.BotdServerOperations.java

public static void CastVote(final Activity activity, final Handler handler, final String email,
        final String shopId, final String shopRef) {
    new Thread() {
        @Override// www.  j  a va 2  s  .co  m
        public void run() {
            try {
                URI uri = new URI(activity.getResources().getString(R.string.server_url));
                HttpClient client = new DefaultHttpClient();
                HttpPut put = new HttpPut(uri);

                JSONObject voteObj = new JSONObject();

                // user's phone-account-email-address is used to prevent multiple votes
                // the server will validate. 'shopId' is a consistent id for a specific location
                // but can't be used to get more data. 'shopRef' is an id that changes based on
                // some criteria that google places has imposed, but will let us grab data later on
                // and various Ref codes with the same id will always resolve to the same location.
                voteObj.put(JSONvalues.email.toString(), email);
                voteObj.put(JSONvalues.shopId.toString(), shopId);
                voteObj.put(JSONvalues.shopRef.toString(), shopRef);
                put.setEntity(new StringEntity(voteObj.toString()));

                HttpResponse response = client.execute(put);
                InputStream is = response.getEntity().getContent();
                int ch;
                StringBuffer sb = new StringBuffer();
                while ((ch = is.read()) != -1) {
                    sb.append((char) ch);
                }
                if (sb.toString().equals("0")) {
                    Utils.PostToastMessageToHandler(handler, "Vote cast!", Toast.LENGTH_SHORT);
                    // Set a local flag to prevent duplicate voting
                    SharedPreferences settings = activity.getSharedPreferences(Const.GenPrefs, 0);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putLong(Const.LastVoteDate, Utils.GetDate());
                    editor.commit();
                } else {
                    // The user shouldn't see this. The above SharedPreferences code will be evaluated
                    // when the user hits the Vote button. If the user gets sneaky and deletes local data though,
                    // the server will catch the duplicate vote based on the user's email address and send back a '1'.
                    Utils.PostToastMessageToHandler(handler,
                            "Vote refused. You've probably already voted today.", Toast.LENGTH_LONG);
                }
                GetTopTen(activity, handler, true);
                // Catch blocks. Return a generic error if anything goes wrong.
                //TODO: implement some better/more appropriate error handling.
            } catch (URISyntaxException usex) {
                usex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (UnsupportedEncodingException ueex) {
                ueex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (ClientProtocolException cpex) {
                cpex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (IOException ioex) {
                ioex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            } catch (JSONException jex) {
                jex.printStackTrace();
                Utils.PostToastMessageToHandler(handler,
                        "There was a problem submitting your vote. Poor signal? Please try again.",
                        Toast.LENGTH_LONG);
            }
        }
    }.start();
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Launch Collect with the given Intent. This method should be used rather
 * than launching the Intent yourself if the row is going to be added into a
 * table other than that which you are currently displaying. This method
 * handles storing the table id of that table so that it can be reclaimed when
 * the activity returns.//from  w  w  w. ja  va2  s . c o m
 * <p>
 * Launches with the return code
 * {@link Constants.RequestCodes.ADD_ROW_COLLECT}.
 * 
 * @param activityToAwaitReturn
 * @param collectAddIntent
 * @param tableId
 */
public static void launchCollectToAddRow(Activity activityToAwaitReturn, Intent collectAddIntent,
        String tableId) {
    // We want to save the id of the table that is going to receive the row
    // that returns from Collect. We'll store it in a SharedPreference so
    // that we can get at it.
    SharedPreferences preferences = activityToAwaitReturn.getSharedPreferences(SHARED_PREFERENCE_NAME,
            Context.MODE_PRIVATE);
    preferences.edit().putString(PREFERENCE_KEY_TABLE_ID_ADD, tableId).commit();
    activityToAwaitReturn.startActivityForResult(collectAddIntent, Constants.RequestCodes.ADD_ROW_COLLECT);
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

@Override
protected void pluginInitialize() {
    gWebView = this.webView;

    Activity activity = this.cordova.getActivity();

    settings = activity.getSharedPreferences("TSLocationManager", 0);
    Settings.init(settings);/* w  w w  .j  a  v  a  2s.com*/

    toneGenerator = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 100);

    Intent launchIntent = activity.getIntent();
    if (launchIntent.hasExtra("forceReload")) {
        // When Activity is launched due to forceReload, minimize the app.
        activity.moveTaskToBack(true);
    }
}

From source file:org.opendatakit.tables.utils.CollectUtil.java

/**
 * Launch collect with the given intent. This method should be used rather
 * than launching the activity yourself because the rowId needs to be retained
 * in order to update the database.//from   w  w w . j ava2  s .c  om
 *
 * @param activityToAwaitReturn
 * @param collectEditIntent
 * @param rowId
 */
public static void launchCollectToEditRow(Activity activityToAwaitReturn, Intent collectEditIntent,
        String rowId) {
    // We want to be able to launch an edit row action from a variety of
    // different activities, such as the spreadsheet and the webviews. In
    // order to update the database, we must know what the row id of the row
    // was which we are editing. There appears to be no way to pass this
    // information to collect and have it return it to us, so we're going to
    // store it in a shared preference.
    //
    // Note that we aren't storing this in the key value store because it is
    // a very temporary bit of state that would be meaningless if the call
    // and return to/from collect was interrupted.
    SharedPreferences preferences = activityToAwaitReturn.getSharedPreferences(SHARED_PREFERENCE_NAME,
            Context.MODE_PRIVATE);
    preferences.edit().putString(PREFERENCE_KEY_EDITED_ROW_ID, rowId).commit();
    activityToAwaitReturn.startActivityForResult(collectEditIntent, Constants.RequestCodes.EDIT_ROW_COLLECT);
}

From source file:com.deltadna.android.sdk.ads.core.AdServiceImpl.java

AdServiceImpl(Activity activity, AdServiceListener listener, String sdkVersion) {

    Preconditions.checkArg(activity != null, "activity cannot be null");
    Preconditions.checkArg(listener != null, "listener cannot be null");

    Log.d(BuildConfig.LOG_TAG, "Initialising AdService version " + VERSION);

    String version = "";
    int versionCode = -1;
    try {//  w w  w .j a v a  2 s  .  c  o m
        final PackageInfo info = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);

        version = info.versionName;
        versionCode = info.versionCode;
    } catch (PackageManager.NameNotFoundException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to read app versions", e);
    }
    exceptionHandler = new ExceptionHandler(activity.getApplicationContext(), version, versionCode, sdkVersion,
            BuildConfig.VERSION_NAME);
    Thread.setDefaultUncaughtExceptionHandler(exceptionHandler);

    this.activity = activity;
    this.listener = MainThread.redirect(listener, AdServiceListener.class);

    metrics = new AdMetrics(
            activity.getSharedPreferences(Preferences.METRICS.preferencesName(), Context.MODE_PRIVATE));
    broadcasts = LocalBroadcastManager.getInstance(activity.getApplicationContext());
    adAgentListeners = Collections
            .unmodifiableSet(new HashSet<>(Arrays.asList(new AgentListener(), new Broadcaster())));

    // dynamically load the DebugReceiver
    try {
        @SuppressWarnings("unchecked")
        final Class<BroadcastReceiver> cls = (Class<BroadcastReceiver>) Class
                .forName("com.deltadna.android.sdk.ads.debug.DebugReceiver");
        broadcasts.registerReceiver(cls.newInstance(), Actions.FILTER);
        Log.d(BuildConfig.LOG_TAG, "DebugReceiver registered");
    } catch (ClassNotFoundException ignored) {
        Log.d(BuildConfig.LOG_TAG, "DebugReceiver not found in classpath");
    } catch (IllegalAccessException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to load DebugReceiver", e);
    } catch (InstantiationException e) {
        Log.w(BuildConfig.LOG_TAG, "Failed to load DebugReceiver", e);
    }
}

From source file:org.uguess.android.sysinfo.ProcessManager.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Activity ctx = getActivity();

    if (item.getItemId() == MI_PREFERENCE) {
        Intent it = new Intent(ctx, ProcessSettings.class);

        it.putExtra(PREF_KEY_REFRESH_INTERVAL,
                Util.getIntOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_REFRESH_INTERVAL, REFRESH_LOW));
        it.putExtra(PREF_KEY_SORT_ORDER_TYPE,
                Util.getIntOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SORT_ORDER_TYPE, ORDER_TYPE_NAME));
        it.putExtra(PREF_KEY_SORT_DIRECTION,
                Util.getIntOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SORT_DIRECTION, ORDER_ASC));
        it.putExtra(PREF_KEY_IGNORE_ACTION,
                Util.getIntOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_IGNORE_ACTION, IGNORE_ACTION_HIDDEN));
        it.putExtra(PREF_KEY_DEFAULT_TAP_ACTION,
                Util.getIntOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_DEFAULT_TAP_ACTION, ACTION_MENU));
        it.putStringArrayListExtra(PREF_KEY_IGNORE_LIST,
                getIgnoreList(ctx.getSharedPreferences(PSTORE_PROCESSMANAGER, Context.MODE_PRIVATE)));
        it.putExtra(PREF_KEY_SHOW_MEM, Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_MEM));
        it.putExtra(PREF_KEY_SHOW_CPU, Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_CPU));
        it.putExtra(PREF_KEY_SHOW_SYS_PROC,
                Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_SYS_PROC));
        it.putExtra(PREF_KEY_SHOW_KILL_WARN,
                Util.getBooleanOption(ctx, PSTORE_PROCESSMANAGER, PREF_KEY_SHOW_KILL_WARN));

        startActivityForResult(it, 1);/*  w w w  .  j  a v a  2 s.c  om*/

        return true;
    }

    return false;
}