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.github.socialc0de.gsw.android.MainActivity.java

/**
 * Called to sign out the user, so user can later on select a different account.
 *
 * @param activity activity that initiated the sign out.
 */// w w w  .j  a v  a 2s.  co  m
static void onSignOut(Activity activity) {
    SharedPreferences settings = activity.getSharedPreferences("reguees", 0);

    SharedPreferences.Editor editor = settings.edit();
    editor.putString(ACCOUNT_NAME_SETTING_NAME, "");

    editor.commit();
    credential.setSelectedAccountName("");

    Intent intent = new Intent(activity, MainActivity.class);
    activity.startActivity(intent);
}

From source file:edu.rowan.app.fragments.FoodRatingFragment.java

/**
 * Start pre-fetching data (load data before it is needed)
 * //  w  ww .ja v a 2  s .c  o m
 * @param reference Activity reference required for AQuery
 */
public static void prefetch(Activity reference, boolean updateCache, FoodRatingFragment callback) {
    SharedPreferences prefs = reference.getSharedPreferences(FoodRatingFragment.PREFS, 0);
    if (!prefs.contains(FoodRatingFragment.USER_ID)) { // we need to get a userId
        getUserID(reference);
    }
    long lastUpdate = prefs.getLong(LAST_REFRESH, 0);
    // [difference] / (milis * seconds * minutes)
    int hourDifference = (int) (Calendar.getInstance().getTimeInMillis() - lastUpdate) / (1000 * 60 * 60);
    Log.d("FoodRatingFragment", "Hour difference: " + hourDifference);
    if (updateCache || hourDifference > UPDATE_INTERVAL || lastUpdate == 0) {
        Log.d("FoodRatingFragment", "Fetching Ratings");
        fetchAllRatings(reference, callback);
    } else {
        Log.d("FoodRatingFragment", "Cached food ratings");
        Log.d("Marketplace",
                prefs.getString(Integer.toString(prefs.getInt(TYPE_MARKETPLACE, 0)), "CACHE FAIL"));
        Log.d("Smokehouse", prefs.getString(Integer.toString(prefs.getInt(TYPE_SMOKEHOUSE, 0)), "CACHE FAIL"));

    }
}

From source file:com.tesobe.hello_obp.lib.OBPRestClient.java

public static boolean getAndSetAccessToken(Activity activity, String verifyCode) {
    try {//from   ww  w .ja va  2s.co  m
        provider.retrieveAccessToken(consumer, verifyCode);
        String token = consumer.getToken();
        String secret = consumer.getTokenSecret();
        if (token != null && secret != null) {
            Editor editor = activity.getSharedPreferences(PREF_FILE, Activity.MODE_PRIVATE).edit();
            editor.putString(CONSUMER_TOKEN, token);
            editor.putString(CONSUMER_SECRET, secret);
            return editor.commit();
        } else
            return false;
    } catch (OAuthMessageSignerException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthNotAuthorizedException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthExpectationFailedException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    } catch (OAuthCommunicationException e) {
        Log.w(LOG_TAG, Log.getStackTraceString(e));
    }
    return false;
}

From source file:com.example.volunteerhandbook.MainActivity.java

public static String getCitizenId(Activity mAty) {
    String fileName = MainActivity.getFileHeader() + mAty.getResources().getString(R.string.login_page);
    SharedPreferences sharedPref = mAty.getSharedPreferences(fileName, Context.MODE_PRIVATE);
    return sharedPref.getString(MainActivity.CITIZEN_ID, "--");
}

From source file:com.android.argb.edhlc.Utils.java

public static ActivePlayer loadPlayerFromSharedPreferences(Activity activity, int tag) {
    SharedPreferences prefs = activity.getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE);
    String pName = prefs.getString(tag + Constants.CURRENT_GAME_PLAYER_NAME, "");
    String pPlayerDeck = prefs.getString(tag + Constants.CURRENT_GAME_PLAYER_DECK, "");
    int[] pColor = {
            prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_COLOR1,
                    ContextCompat.getColor(activity.getApplicationContext(), R.color.primary_color)),
            prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_COLOR1,
                    ContextCompat.getColor(activity.getApplicationContext(), R.color.primary_color)) };
    boolean pIsAlive = prefs.getBoolean(tag + Constants.CURRENT_GAME_PLAYER_IS_ALIVE, true);
    int pLife = prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_LIFE, 40);
    int pEDH1 = prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_EDH1, 0);
    int pEDH2 = prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_EDH2, 0);
    int pEDH3 = prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_EDH3, 0);
    int pEDH4 = prefs.getInt(tag + Constants.CURRENT_GAME_PLAYER_EDH4, 0);

    return new ActivePlayer(new Deck(pName, pPlayerDeck, pColor), pIsAlive, pLife, pEDH1, pEDH2, pEDH3, pEDH4,
            tag);/*from   w ww  .  j a v a  2 s.  co m*/
}

From source file:it.feio.android.omninotes.BaseActivity.java

/**
 * Method to validate security password to protect notes.
 * It uses an interface callback./*from  w  w  w .  ja va 2  s . c  o  m*/
 */
public static void requestPassword(final Activity mActivity, final PasswordValidator mPasswordValidator) {

    // Inflate layout
    LayoutInflater inflater = mActivity.getLayoutInflater();
    final View v = inflater.inflate(R.layout.password_request_dialog_layout, null);
    final EditText passwordEditText = (EditText) v.findViewById(R.id.password_request);

    MaterialDialog dialog = new MaterialDialog.Builder(mActivity).autoDismiss(false)
            .title(R.string.insert_security_password).customView(v, false).positiveText(R.string.ok)
            .callback(new MaterialDialog.ButtonCallback() {
                @Override
                public void onPositive(MaterialDialog dialog) {
                    // When positive button is pressed password correctness is checked
                    String oldPassword = mActivity
                            .getSharedPreferences(Constants.PREFS_NAME, MODE_MULTI_PROCESS)
                            .getString(Constants.PREF_PASSWORD, "");
                    String password = passwordEditText.getText().toString();
                    // The check is done on password's hash stored in preferences
                    boolean result = Security.md5(password).equals(oldPassword);

                    // In case password is ok dialog is dismissed and result sent to callback
                    if (result) {
                        KeyboardUtils.hideKeyboard(passwordEditText);
                        dialog.dismiss();
                        mPasswordValidator.onPasswordValidated(true);
                        // If password is wrong the auth flow is not interrupted and simply a message is shown
                    } else {
                        passwordEditText.setError(mActivity.getString(R.string.wrong_password));
                    }
                }
            }).build();

    dialog.setOnCancelListener(dialog1 -> {
        KeyboardUtils.hideKeyboard(passwordEditText);
        dialog1.dismiss();
        mPasswordValidator.onPasswordValidated(false);
    });

    dialog.show();

    // Force focus and shows soft keyboard
    new Handler().postDelayed(() -> KeyboardUtils.showKeyboard(passwordEditText), 100);
}

From source file:com.android.argb.edhlc.Utils.java

public static void savePlayerInSharedPreferences(Activity activity, ActivePlayer activePlayer) {
    SharedPreferences.Editor editor = activity
            .getSharedPreferences(Constants.PREFERENCE_NAME, Activity.MODE_PRIVATE).edit();
    editor.putString(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_NAME,
            activePlayer.getPlayerDeck().getDeckOwnerName());
    editor.putString(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_DECK,
            activePlayer.getPlayerDeck().getDeckName());
    editor.putBoolean(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_IS_ALIVE,
            activePlayer.getPlayerIsAlive());
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_COLOR1,
            activePlayer.getPlayerDeck().getDeckShieldColor()[0]);
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_LIFE,
            activePlayer.getPlayerLife());
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_EDH1,
            activePlayer.getPlayerEDH1());
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_EDH2,
            activePlayer.getPlayerEDH2());
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_EDH3,
            activePlayer.getPlayerEDH3());
    editor.putInt(activePlayer.getPlayerTag() + Constants.CURRENT_GAME_PLAYER_EDH4,
            activePlayer.getPlayerEDH4());
    editor.apply();/*from  w w  w  .ja  v a 2 s  .  c  om*/
}

From source file:com.apptentive.android.sdk.Apptentive.java

/**
 * Launches Apptentive features based on a push notification Intent. Before you call this, you must call
 * {@link Apptentive#setPendingPushNotification(Context, Intent)} in your Broadcast receiver when a push notification
 * is opened by the user. This method must be called from the Activity that you launched from the
 * BroadcastReceiver. This method will only handle Apptentive originated push notifications, so call is any time you
 * receive a push./*w ww. j  a  v a  2  s  .co m*/
 * <p/>
 * <strong>Note: </strong>If you are using Parse, do not use this method. Instead, see the Apptentive
 * <a href="http://www.apptentive.com/docs/android/integration/"> integration guide</a> for Parse.
 *
 * @param activity The Activity from which this method is called.
 * @return True if a call to this method resulted in Apptentive displaying a View.
 */
public static boolean handleOpenedPushNotification(Activity activity) {
    SharedPreferences prefs = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    String pushData = prefs.getString(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION, null);
    prefs.edit().remove(Constants.PREF_KEY_PENDING_PUSH_NOTIFICATION).commit(); // Remove our data so this won't run twice.
    if (pushData != null) {
        Log.i("Handling Apptentive Push Intent.");
        try {
            JSONObject pushJson = new JSONObject(pushData);
            ApptentiveInternal.PushAction action = ApptentiveInternal.PushAction.unknown;
            if (pushJson.has(ApptentiveInternal.PUSH_ACTION)) {
                action = ApptentiveInternal.PushAction
                        .parse(pushJson.getString(ApptentiveInternal.PUSH_ACTION));
            }
            switch (action) {
            case pmc:
                Apptentive.showMessageCenter(activity);
                return true;
            default:
                Log.v("Unknown Push Notification Action \"%s\"", action.name());
            }
        } catch (JSONException e) {
            Log.w("Error parsing JSON from push notification.", e);
            MetricModule.sendError(activity.getApplicationContext(), e, "Parsing Push notification", pushData);
        }
    }
    return false;
}

From source file:edu.rowan.app.fragments.FoodRatingFragment.java

private static void fetchRating(JsonQueryManager jsonQuery, final String foodType, final Activity reference,
        final FoodRatingFragment callback) {
    final String address = FOOD_RATING_ADDR;
    Map<String, String> params = new HashMap<String, String>();
    params.put("type", foodType);
    jsonQuery.requestJson(address, params, new Callback() {
        @Override//from   w  ww  .j  a v  a  2 s . c om
        public void receiveJson(JSONObject json, String origin) {
            try {
                if (origin == address) {
                    if (json != null) {
                        SharedPreferences prefs = reference.getSharedPreferences(PREFS, 0);
                        updatePreferencesData(prefs, foodType, json);
                        Log.d("Homescreen", "saved json: " + json.toString());
                        // make sure callback is still an active fragment
                        if (callback != null && callback.isResumed()) {
                            callback.ratingsUpdated(reference);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
}

From source file:com.dwdesign.tweetings.fragment.BaseDialogFragment.java

public SharedPreferences getSharedPreferences(final String name, final int mode) {
    final Activity activity = getActivity();
    if (activity != null)
        return activity.getSharedPreferences(name, mode);
    return null;//from ww w .ja va 2s.com
}