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.project.qrypto.keymanagement.KeyManager.java

public void init(Activity context) throws InvalidCipherTextException, IOException {
    if (!storeLoaded) {
        SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE);
        internalStorage = preferences.getBoolean(USE_INTERNAL_STORAGE, true);
        passwordProtected = preferences.getBoolean(PASSWORD_PROTECTED, true);
        setupComplete = preferences.getBoolean(SETUP_COMPLETE, false);
        if (passwordProtected) {
            Intent intent = new Intent(context, SetupActivity.class);
            context.startActivity(intent);
        } else {/*from   www.j a  va2 s. c  o  m*/
            load(context);
        }
    }
}

From source file:net.zionsoft.obadiah.ui.fragments.TranslationListFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    setRetainInstance(true);//from ww w  .j  a v a 2 s. c om
    mPreferences = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
    mCurrentTranslation = mPreferences.getString(Constants.PREF_KEY_LAST_READ_TRANSLATION, null);
}

From source file:io.nuclei.cyto.share.PackageTargetManager.java

/**
 * Send the startActivityForResult intent to an activity
 *
 * @param requestCode The request code to listen to in the onActivityResult
 *//*ww  w  .java  2s . c  o  m*/
public void onShare(Activity activity, Intent intent, int requestCode) {
    if (mWeights == null)
        mWeights = activity.getSharedPreferences(DEFAULT_SHARE_WEIGHTS, Context.MODE_PRIVATE);
    int weight = mWeights.getInt(intent.getComponent().getClassName(), 0) + 1;
    mWeights.edit().putInt(intent.getComponent().getClassName(), weight).apply();
    activity.startActivityForResult(intent, requestCode);
}

From source file:de.vanita5.twittnuker.fragment.support.BaseSupportListFragment.java

public final SharedPreferences getSharedPreferences(final String name, final int mode) {
    final Activity activity = getActivity();
    if (activity != null)
        return activity.getSharedPreferences(name, mode);
    return null;// ww w  . ja v  a2  s  .  c o  m
}

From source file:com.handlerexploit.news.fragments.WeatherFragment.java

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

    final Activity activity = getActivity();
    if (activity != null) {
        threadPool.execute(new Runnable() {
            public void run() {
                final SharedPreferences sharedPreferences = activity.getSharedPreferences(".preferences",
                        Context.MODE_PRIVATE);
                String location = sharedPreferences.getString("Location", null);
                if (location != null) {
                    final WeatherInfo weatherInfo = WeatherProvider.getWeather(location);
                    handler.post(new Runnable() {
                        public void run() {
                            render(weatherInfo);
                        }/* w ww.ja v  a2s  .  c  o m*/
                    });
                } else {
                    Location lastKnownLocation = ((LocationManager) activity
                            .getSystemService(Context.LOCATION_SERVICE))
                                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (lastKnownLocation != null) {
                        double longitude = lastKnownLocation.getLongitude();
                        double latitude = lastKnownLocation.getLatitude();

                        String url = "http://maps.google.com/maps/geo?ll=" + latitude + "," + longitude;
                        try {
                            String response = EntityUtils
                                    .toString(new DefaultHttpClient().execute(new HttpGet(url)).getEntity());
                            JSONObject addressDetails = new JSONObject(response).getJSONArray("Placemark")
                                    .getJSONObject(0).getJSONObject("AddressDetails");
                            JSONObject locality = addressDetails.getJSONObject("Country")
                                    .getJSONObject("AdministrativeArea").getJSONObject("Locality");

                            String raw;
                            if (locality.get("PostalCode") == null) {
                                raw = locality.getString("LocalityName");
                            } else {
                                raw = locality.getJSONObject("PostalCode").getString("PostalCodeNumber");
                            }

                            sharedPreferences.edit().putString("Location", raw).commit();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } catch (ParseException e) {
                            e.printStackTrace();
                        } catch (ClientProtocolException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } else {
                        sharedPreferences.edit().putString("Location", "Miami").commit();
                    }

                    final WeatherInfo weatherInfo = WeatherProvider.getWeather("Miami");
                    if (weatherInfo != null) {
                        handler.post(new Runnable() {
                            public void run() {
                                render(weatherInfo);
                            }
                        });
                    }
                }
            }
        });
    }
}

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

private SharedPreferences.Editor editPreferences(Activity activity) {
    return activity.getSharedPreferences(PREFS_KEY, Context.MODE_PRIVATE).edit();
}

From source file:com.alley.android.ppi.app.OverviewFragment.java

private void readCameraSettingsFromPreferences() {
    Activity activity = getActivity();
    if (latitude == 0 && longitude == 0 && zoom == 0 && activity != null) {
        SharedPreferences settings = activity.getSharedPreferences("MAP_SETTINGS", 0);
        latitude = settings.getFloat("latitude", (float) 0);
        longitude = settings.getFloat("longitude", (float) 0);
        zoom = settings.getFloat("zoom", 0);
        //Log.i(LOG_TAG, "readCameraSettingsFromPreferences read from preferences latitude:" + latitude + " longtitude:" + longitude + " zoom:" + zoom);
    }/*from w w w.  j a v a2s. co m*/
}

From source file:net.texh.cordovapluginstepcounter.CordovaStepCounter.java

@Override
public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
    LOG.i(TAG, "execute()");
    Boolean result = true;//  w w  w .j ava 2 s .c o  m

    Activity activity = this.cordova.getActivity();
    stepCounterIntent = new Intent(activity, StepCounterService.class);

    //Get stored value for pedometerActive
    SharedPreferences sharedPref = activity.getSharedPreferences(USER_DATA_PREF, Context.MODE_PRIVATE);
    Boolean pActive = this.getPedometerIsActive(sharedPref);

    if (ACTION_CAN_COUNT_STEPS.equals(action)) {
        Boolean can = deviceHasStepCounter(activity.getPackageManager());
        Log.i(TAG, "Checking if device has step counter APIS: " + can);
        callbackContext.success(can ? 1 : 0);
    } else if (ACTION_START.equals(action)) {

        if (!pActive) {
            Log.i(TAG, "Starting StepCounterService");
            //Update pedometerActive preference
            this.setPedometerIsActive(sharedPref, true);
            activity.startService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService Already Started before, just binding to it");
        }

        if (!bound) {
            Log.i(TAG, "Binding StepCounterService");
            activity.bindService(stepCounterIntent, mConnection, Context.BIND_AUTO_CREATE);
        } else {
            Log.i(TAG, "StepCounterService already binded");
        }

        //Try getting given param (starting value)
        Integer startingValue = 0;
        try {
            if (data.length() > 0) {
                startingValue = data.getInt(0);
            }
        } catch (JSONException error) {
            Log.i(TAG, "JSON EXCEPTION While Reading startingValue from 'execute' parameters (JSONArray)");
        }

        //Reset TOTAL COUNT on start
        CordovaStepCounter.setTotalCount(sharedPref, startingValue);
        callbackContext.success(startingValue);
    } else if (ACTION_STOP.equals(action)) {
        if (pActive) {
            Log.i(TAG, "Stopping StepCounterService");
            this.setPedometerIsActive(sharedPref, false);
            activity.stopService(stepCounterIntent);
        } else {
            Log.i(TAG, "StepCounterService already stopped");
        }

        if (bound) {
            Log.i(TAG, "Unbinding StepCounterService");
            activity.unbindService(mConnection);
        } else {
            Log.i(TAG, "StepCounterService already unbinded");
        }

        activity.stopService(stepCounterIntent);
        Integer currentCount = CordovaStepCounter.getTotalCount(sharedPref);
        //Callback with final count
        callbackContext.success(currentCount);
    } else if (ACTION_GET_STEPS.equals(action)) {
        if (!pActive) {
            Log.i(TAG, "Be Careful you're getting a Step count with inactive Pedometer");
        }

        Integer steps = CordovaStepCounter.getTotalCount(sharedPref);
        Log.i(TAG, "Geting steps counted from stepCounterService: " + steps);
        callbackContext.success(steps);
    } else if (ACTION_GET_TODAY_STEPS.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");

            Date currentDate = new Date();
            SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
            String currentDateString = dateFormatter.format(currentDate);

            JSONObject pData = new JSONObject();
            JSONObject dayData = new JSONObject();
            Integer daySteps = -1;
            try {
                pData = new JSONObject(pDataString);
                Log.d(TAG, " got json shared prefs " + pData.toString());
            } catch (JSONException err) {
                Log.d(TAG, " Exception while parsing json string : " + pDataString);
            }

            if (pData.has(currentDateString)) {
                try {
                    dayData = pData.getJSONObject(currentDateString);
                    daySteps = dayData.getInt("steps");
                } catch (JSONException err) {
                    Log.e(TAG, "Exception while getting Object from JSON for " + currentDateString);
                }
            }

            Log.i(TAG, "Getting steps for today: " + daySteps);
            callbackContext.success(daySteps);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success(-1);
        }
    } else if (ACTION_GET_HISTORY.equals(action)) {
        if (sharedPref.contains(PEDOMETER_HISTORY_PREF)) {
            String pDataString = sharedPref.getString(PEDOMETER_HISTORY_PREF, "{}");
            Log.i(TAG, "Getting steps history from stepCounterService: " + pDataString);
            callbackContext.success(pDataString);
        } else {
            Log.i(TAG, "No steps history found in stepCounterService !");
            callbackContext.success("{}");
        }
    } else {
        Log.e(TAG, "Invalid action called on class " + TAG + ", " + action);
        callbackContext.error("Invalid action called on class " + TAG + ", " + action);
    }

    return result;
}

From source file:com.apptentive.android.sdk.module.messagecenter.ApptentiveMessageCenter.java

static void showIntroDialog(final Activity activity, boolean emailRequired) {
    final MessageCenterIntroDialog dialog = new MessageCenterIntroDialog(activity);
    dialog.setEmailRequired(emailRequired);

    String personEnteredEmail = PersonManager.loadPersonEmail(activity);
    String personInitialEmail = PersonManager.loadInitialPersonEmail(activity);
    if (Util.isEmpty(personEnteredEmail)) {
        if (!Util.isEmpty(personInitialEmail)) {
            dialog.setEmailFieldHidden(false);
            dialog.prePopulateEmail(personInitialEmail);
        }//w ww.j a v a 2s. c om
    } else {
        dialog.setEmailFieldHidden(true);
    }
    dialog.setCanceledOnTouchOutside(false);

    dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialogInterface) {
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__cancel);
            dialog.dismiss();
        }
    });

    dialog.setOnSendListener(new MessageCenterIntroDialog.OnSendListener() {
        @Override
        public void onSend(String email, String message) {
            SharedPreferences prefs = activity.getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE);
            prefs.edit().putBoolean(Constants.PREF_KEY_MESSAGE_CENTER_SHOULD_SHOW_INTRO_DIALOG, false).commit();
            // Save the email.
            if (dialog.isEmailFieldVisible()) {
                if (email != null && email.length() != 0) {
                    PersonManager.storePersonEmail(activity, email);
                    Person person = PersonManager.storePersonAndReturnDiff(activity);
                    if (person != null) {
                        Log.d("Person was updated.");
                        Log.v(person.toString());
                        ApptentiveDatabase.getInstance(activity).addPayload(person);
                    } else {
                        Log.d("Person was not updated.");
                    }
                }
            }
            // Send the message.
            final TextMessage textMessage = new TextMessage();
            textMessage.setBody(message);
            textMessage.setRead(true);
            textMessage.setCustomData(customData);
            customData = null;
            MessageManager.sendMessage(activity, textMessage);
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__send);
            dialog.dismiss();

            final MessageCenterThankYouDialog messageCenterThankYouDialog = new MessageCenterThankYouDialog(
                    activity);
            messageCenterThankYouDialog.setValidEmailProvided(email != null && Util.isEmailValid(email));
            messageCenterThankYouDialog
                    .setOnChoiceMadeListener(new MessageCenterThankYouDialog.OnChoiceMadeListener() {
                        @Override
                        public void onNo() {
                            MetricModule.sendMetric(activity,
                                    Event.EventLabel.message_center__thank_you__close);
                        }

                        @Override
                        public void onYes() {
                            MetricModule.sendMetric(activity,
                                    Event.EventLabel.message_center__thank_you__messages);
                            show(activity);
                        }
                    });
            MetricModule.sendMetric(activity, Event.EventLabel.message_center__thank_you__launch);
            messageCenterThankYouDialog.show();
        }
    });

    String appDisplayName = Configuration.load(activity).getAppDisplayName();
    switch (trigger) {
    case enjoyment_dialog:
        dialog.setTitle(R.string.apptentive_intro_dialog_title_no_love);
        dialog.setBody(
                activity.getResources().getString(R.string.apptentive_intro_dialog_body, appDisplayName));
        break;
    case message_center:
        dialog.setTitle(R.string.apptentive_intro_dialog_title_default);
        dialog.setBody(
                activity.getResources().getString(R.string.apptentive_intro_dialog_body, appDisplayName));
        break;
    default:
        return;
    }
    MetricModule.sendMetric(activity, Event.EventLabel.message_center__intro__launch, trigger.name());
    dialog.show();
}

From source file:com.dycody.android.idealnote.SettingsFragment.java

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.activity = activity;
    prefs = activity.getSharedPreferences(Constants.PREFS_NAME, Context.MODE_MULTI_PROCESS);
    setTitle();/* w  w w. j  av  a 2 s  .  com*/
}