I'm building my first multi-activity app. I have some geographic coordinates in Activity1 that are defined by the user and are saved to SharedPreferences:
// these strings are used when saving the users' preferred location
private static final String POINT_LATITUDE_KEY = "POINT_LATITUDE_KEY";
private static final String POINT_LONGITUDE_KEY = "POINT_LONGITUDE_KEY";
private static final String TAG = "Activity1";
// actually saves the coordinates to the preferences
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs =
this.getSharedPreferences(getClass().getSimpleName(),
Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putFloat(POINT_LATITUDE_KEY, latitude);
prefsEditor.putFloat(POINT_LONGITUDE_KEY, longitude);
//Log.i(TAG, "latitude is: " + latitude);
//Log.i(TAG, "longitude is: " + longitude);
prefsEditor.commit();
}
These SharedPreferences coordinates then need to be used by Activity2. I'm having trouble retrieving them. Here's a method I have written for retrieval. My variable latitude is not written to the log.
private static final String TAG = "Activity2";
protected void getLatLongPref() {
// adapted from http://mrbool.com/android-shared-preferences-managing-files-using-internal-external-storage/30508
// accessed April 10, 2015
SharedPreferences pref = getApplicationContext().getSharedPreferences("POINT_LATITUDE_KEY", MODE_PRIVATE);
float latitudeUser = pref.getFloat("POINT_LATITUDE_KEY", 0); // getting users chosen latitude
Log.i(TAG, "latitude is: " + latitudeUser);
}
What do you think I'm doing wrong ?
You have used wrong context and preference name for both sharedpreferences. Change the first one to this:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("POINT_LATITUDE_KEY",
Context.MODE_PRIVATE);
Change your first code snippet like this:
private void saveCoordinatesInPreferences(float latitude, float longitude) {
SharedPreferences prefs =
this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
[...]
}
...And your second one like this:
protected void getLatLongPref() {
SharedPreferences pref =
this.getSharedPreferences("myPref", Context.MODE_PRIVATE);
[...]
}
Basically, It has to be the same in both cases. See this also.
Related
Im trying to make an EULA for my app, but there is a different EULA for the different countries we work with.
my idea was that i save a String in SharedPreferences like ZA for South Africa and KE for Kenya. So if you click the South Africa button, it will save the string in SharedPreferences as ZA and the same for Kenya. Once the button has been clicked it the new activity will then load the appropriate EULA by pulling the ZA or KE string from the SharedPreferences. This is what i have at the moment:
Country_select.java
public class country_select extends Activity {
private static final String TAG = "Logs";
public static final String PREFS_NAME = "PrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_country_select);
final Button za_button = (Button) findViewById(R.id.btn_za);
Button ke_button = (Button) findViewById(R.id.btn_ke);
Log.i(TAG, "created buttons");
za_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "ZA");
editor.commit();
}
});
Log.i(TAG, "set button settings for ZA");
ke_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Country_Selected", "KE");
editor.commit();
}
});
Log.i(TAG, "set button settings for KE");
}
I may have this totally incorrect but on the layout file there are 2 buttons, one for KE and one for ZA.
I would like it, when the new activity is loaded to read SharedPreferences whether it has ZA or KE? Is what i have done here correct?
Thank you
I think you're better off with using IntentExtras, in your first activity upon clicking the country button store the value inside a variable and when you want to start the new activity pass the data as an intent extra:
Intent intent= new Intent(getActivity(), NewActivity.class);
intent.putExtra("country", countryCode);
startActivity(intent);
And then inside the new activity you can retrieve the value like this:
String countryCode = getIntent().getExtras().getString("country");
In order to maintain Shared preference across the application i use it this way
, take a look
I saved a AppPrefes class as a seprate class in the package
public class AppPrefes {
private SharedPreferences appSharedPrefs;
private Editor prefsEditor;
public AppPrefes(Context context, String Preferncename) {
this.appSharedPrefs = context.getSharedPreferences(Preferncename,
Activity.MODE_PRIVATE);
this.prefsEditor = appSharedPrefs.edit();
}
/****
*
* getdata() get the value from the preference
*
* */
public String getData(String key) {
return appSharedPrefs.getString(key, "");
}
public Integer getIntData(String key) {
return appSharedPrefs.getInt(key, 0);
}
/****
*
* SaveData() save the value to the preference
*
* */
public void SaveData(String Tag, String text) {
prefsEditor.putString(Tag, text);
prefsEditor.commit();
}
public void SaveIntData(String key, int value) {
prefsEditor.putInt(key, value);
prefsEditor.commit();
}
/**
* delete all AppPreference
*/
public void deleteAll() {
this.prefsEditor = appSharedPrefs.edit();
this.prefsEditor.clear();
this.prefsEditor.commit();
}
In your Activity or Fragment were you would like to get or save data just use it like this
Decalre an object for the AppPrefes class
AppPrefes appPref;
Initialize in onCreate
appPref = new AppPrefes(getActivity(), "type name of your preference");
To save data to the preference use
appPref.SaveData("tag_name", "value to be saved);
To get data from the preference
appPref.getData("tag_name");
You can also save Integer values and clear all preference values if necessary just call the apporopriate methods.
Yes, the storing part is correct. Now you will need to access the stored value in your new activity.
Example-
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
String storedCountry = sharedpreferences.getString("Country_Selected"); // could be null value if there is no value stored with Country_Selected tag.
I am having issues loading the sharedpreferences. This is my first app with no prior coding experience. The app allows the user to count their number of "Drinks" and "Shots".
The buttons increase their appropriate textView by "1". When I close the app and open it the numbers stay intact and the buttons keep increasing the value by "1".
The problem is When the app is destroyed and opened. The textView's will show the numbers that were left, but when I press a button they rest back to 1. So, the the correct numbers are being loaded, but the buttons are resting those numbers.
I hope this is clear enough. Please, let me know if I need to explain it better. I'm usually able to figure out all my problems through a lot of internet searches. I just finally hit a wall.
private Button clearButton;
private Button drinkButton;
private Button shotButton;
private TextView textDrink;
private TextView textShot;
private int counterDrink = 0;
private int counterShot = 0;
public static final String DRINK_DATA = "DrinkData";
public static final String DEFAULT = "0";
SharedPreferences prefs;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
loadSavedPreferences();
}
...
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned); }
'
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String shotData = textShot.getText().toString();
String drinkData = textDrink.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("DrinkData", drinkData);
editor.putString("ShotData", shotData);
editor.commit();
}
`
You forget to initialize the int-counters:
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
String dataDrinkReturned = prefs.getString("DrinkData", DEFAULT);
String dataShotReturned = prefs.getString("ShotData", DEFAULT);
counterDrink = Integer.parseInt(dataDrinkReturned);
counterShot = Integer.parseInt(dataShotReturned );
textDrink.setText(dataDrinkReturned);
textShot.setText(dataShotReturned);
}
Although i feel it would be better than to save the int-values in the shared preferences instead of the string-values.
private void loadSavedPreferences(){
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
counterDrink = prefs.getInt("DrinkData", 0);
counterShot = prefs.getInt("ShotData", 0);
textDrink.setText(""+counterDrink);
textShot.setText(""+counterShot);
}
#Override
protected void onPause(){
super.onPause();
prefs = getSharedPreferences(DRINK_DATA, MODE_PRIVATE);
editor.putInt("DrinkData", counterDrink );
editor.putInt("ShotData", counterShot );
editor.commit();
}
That's because you're not setting the counter variables (counterDrink and counterShot) to the correct amount, and are always reset upon restarting the activity.
Instead of saving the counters to SharedPreferences as a String, I suggest saving it as an integer, and on top of setting the TextViews to the correct amount, you also need to set the counterDrink and counterShot.
This question already has answers here:
Shared Preferences not saving when I compile my code
(3 answers)
Closed 8 years ago.
I am trying to save a simple Highscore to my game, but the data isn't saving to shared preferences.
SharedPrefManager.java:
package com.divergent.thumbler;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all
//shared pref methods from non activity classes.
//because getSharedPreferences required the context.
//but in activity class we can call without this context
private static Context mContext;
// will get user input in below variables, then will store in to shared pref
private static int HighScore;
public static void Init(Context context)
{
mContext = context;
}
public static void LoadFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
// Note here the 2nd parameter 0 is the default parameter for private access,
//Operating mode. Use 0 or MODE_PRIVATE for the default operation,
settings.getInt("HighScore", HighScore);
}
public static void StoreToPref()
{
// get the existing preference file
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighScore", HighScore);
//final step to commit (save)the changes in to the shared pref
editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName)
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.remove(keyName);
editor.commit();
}
public static void DeleteAllEntriesFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
public static void SetHighScore(int score)
{
HighScore = score;
}
public static int getHighScore()
{
return HighScore ;
}
}
I am saving my highscore with the following function:
public void highscoreSaver() {
SharedPrefManager.LoadFromPref();
if(finalScore > SharedPrefManager.getHighScore()) {
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
}
}
And getting my highscore like this:
HighScore = SharedPrefManager.getHighScore();
Is there anything that im doing wrong? Please let me know
I think the problem lies in settings.getInt("HighScore", HighScore);
As per documentation here, SharedPreferences.getInt(String, int) returns an integer, the second parameter is for giving default value if there is no preference with the given key so you should do something like HighScore = settings.getInt("HighScore", 0); instead
I am making a Highscore script for my game using Shared Preferences. I want this data to be only held for the phone it is installed on obviously. I have done the following, and the highscore shows and updates, but when I close out of the app and re open it, it resets.
if(finalScore > SharedPrefManager.getHighScore())
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
SharedPrefManager.java:
package com.divergent.thumbler;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all
//shared pref methods from non activity classes.
//because getSharedPreferences required the context.
//but in activity class we can call without this context
private static Context mContext;
// will get user input in below variables, then will store in to shared pref
private static int HighScore = 0;
public static void Init(Context context)
{
mContext = context;
}
public static void LoadFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
// Note here the 2nd parameter 0 is the default parameter for private access,
//Operating mode. Use 0 or MODE_PRIVATE for the default operation,
HighScore = settings.getInt("HighScore", HighScore);
}
public static void StoreToPref()
{
// get the existing preference file
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighScore", HighScore); // Age is the key and mAge is holding the value
//final step to commit (save)the changes in to the shared pref
editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName)
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.remove(keyName);
editor.commit();
}
public static void DeleteAllEntriesFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
public static void SetHighScore(int score)
{
HighScore = score;
}
public static int getHighScore()
{
return HighScore ;
}
}
Better don't store sensitive information in sharedpreference. All the users that have root permission can see and easily edit your sharedpreference(If it is not encrypted). So dont forget to encrypt all data.
Here is the chunk of code you need to store in sharedpreference
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("finalScore", yourscore);
editor.commit();
UPDATE
You are setting as
editor.putInt("HighScore", HighScore);
and getting as
HighScore = settings.getInt("Age",0);
You should use the same tag
UPDATE
Change
HighScore = settings.getInt("HighScore", HighScore);
to
settings.getInt("HighScore", HighScore);
I'm trying to save some filters/state in one activity, and then use that data in the next activity.
I'm using SharedPreferences, but it isn't working as I'd expected it to.
public class FilterActivity extends Activity {
private static final String TAG = FilterActivity.class.getName();
EditText distanceEditor;
#Override
public void onPause() {
super.onPause();
SharedPreferences preferences = getSharedPreferences(PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE);
String distance = distanceEditor.getText().toString();
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
Log.i(TAG, "Wrote max-distance=" + distance);
Log.i(TAG, "Preferences contains distance=" + preferences.getString(PreferenceKey.DISTANCE, "FAIL"));
}
public static class PreferenceKey {
public static final String FILTER_PREFERENCES_NAME = "FilterActivity:" + "Filter_Preference_File";
public static final String DISTANCE = "FilterActivity:" + "DISTANCE";
}
}
Then, the Activity that should use this preference:
public class MapActivity extends MapActivity {
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getSharedPreferences(FilterActivity.PreferenceKey.FILTER_PREFERENCES_NAME, MODE_WORLD_READABLE);
String maxDistance = preferences.getString(FilterActivity.PreferenceKey.DISTANCE, "FAIL");
Log.i(TAG, "Read max-distance=" + maxDistance);
}
}
But the output I get is:
.FilterActivity( 4847): Wrote max-distance=99.9
.FilterActivity( 4847): Preferences contains distance=FAIL
.MapActivity( 4847): Read max-distance=FAIL
Can anyone tell me what I'm doing wrong here?
I am developing against API Level-8.
In the following two lines,
preferences.edit().putString(PreferenceKey.DISTANCE, distance);
preferences.edit().commit();
two different SharedPreferences.Editors are being returned. Hence the value is not being committed. Instead, you have to use:
SharedPreferences.Editor spe = preferences.edit();
spe.putString(PreferenceKey.DISTANCE, distance);
spe.commit();