Android App - sharedpreferences not loading properly - java

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.

Related

SharedPreferences integer addition

I have a code... Its excellent save data and load data, but... When i reset application, my score loading, but when i click button for +5 score, my score reset and set 5. I am want that addition +5, but its dont work...
I understand that the problem of addition, because save and load working excellent, but addition doesnt work.
Sorry for my bad English :)
int mCounts;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.appli);
Settings = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
score = (TextView) findViewById(R.id.score);
score.setText(String.valueOf(mCounts));
}
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
}
public void onPause() {
super.onPause();
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Try this code in your button:
public void five(View view) {
score.setText(String.valueOf(mCounts += 5)+"");
SharedPreferences.Editor editor = Settings.edit();
editor.putInt(APP_PREFERENCES_SCORE, mCounts);
editor.apply();
}
Problem is here:
int mCounts = Settings.getInt(APP_PREFERENCES_SCORE, 1);
Remove int. it will work

Save variable in SharedPreferences based on which button is clicked

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.

Shared Preferences save and retrieve data

I'm using Shared Preferences to save data from an AutoCompleteTextView.
When the user writes something in this AutoCompleteTextView, he can click a button in order to save what he just wrote (so that he doesn't have to write it every time).
Here's what my code looks like:
private AutoCompleteTextView autoComplete = null;
String nameFile = "Web service data";
String myData = "";
SharedPreferences pref;
Editor editor;
String channel = "";
String[] valuesArray = {channel};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, valuesArray);
autoComplete = (AutoCompleteTextView) findViewById(R.id.autocompletion);
autoComplete.setAdapter(adapter);
Button add = (Button) findViewById(R.id.add);
add.setOnClickListener(sendForm2);
Button remove = (Button) findViewById(R.id.remove);
remove.setOnClickListener(sendForm2);
channel = pref.getString(nameFile, null);
}
OnClickListener sendForm2 = new OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.add:
myData = autoComplete.getText().toString();
editor.putString(nameFile, myData);
editor.commit();
break;
case R.id.remove:
editor.remove(nameFile);
editor.commit();
break;
}
}
};
The problem is, the Shared Preferences doesn't save any data in channel at all. Even when I close the application and restart it.
Any clue or idea how to resolve this problem?
First thing I would try would be to add a
Log.d("OnCreate", "channel : "+ channel);
in the onCreate just after
channel = pref.getString(nameFile, null);
to see if you have something inside.
If you don't, this really means that sharedpref are not saved.
In this case I would try to bring back the :
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
editor = pref.edit();
just before the
switch (v.getId()) {
I remember reading that sometimes depending on what you are doing with your activities, the sharedpref editor you create can be "lost" and not be related to anything later in the code.
Use the following method to save and retrive String prefrence.
//save the prefrence by pasing key and data
public static void SavePrefrence(Context ctx, String Key, String value) {
ctx.getSharedPreferences("mypref", ctx.MODE_PRIVATE)
.edit().putString(Key, value).commit();
}
//get the prefrence by passing your key
public static String getPrefrence(Context ctx, String key) {
SharedPreferences pref = ctx.getSharedPreferences(
"mypref", ctx.MODE_PRIVATE);
String result = pref.getString(key, null);
return result;
}

Storing a string into a permenant variable issue

I'am trying to store a string from a variable (NumberString) to another variable (PermenantString)
When the string is entered in to PermenantString, it should be stored permenantly in that variable, until the app is deleted or i specifically create a button to clear that PermenantString variable.
MainAvtivity
public class MainActivity extends Activity {
public final String PermenantString= "";
verified.class
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.verified);
Button VerifyCompleteButton = (Button) findViewById(R.id.VerifyCompleteButton);
VerifyCompleteButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
String NumberString;
String PermenantString;
//TextView NUMView;
TextView NUMView = (TextView) findViewById(R.id.NUMView);
Bundle bundle = getIntent().getExtras();
NumberString= bundle.getString("NumberString");
PermenantString = bundle.getString("PermenantString");
PermenantString= NumberString.toString();
//set String PermenantString= ""; permenantly
NUMView.setText(PermenantString);
//
}
});
You should use preferences or sqlite to store the data. Check the storage options #
http://developer.android.com/guide/topics/data/data-storage.html
Example:
public static final String PREFS_NAME = "MyPrefsFile";
Then
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key", stringvalue);
editor.commit();
Then to get
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String value = settings.getString("key","defaultstring");
Note that variables are stored in volatile RAM memory. By volatile, I mean that the value is stored only as long as your app is running. This is the very opposite of the permanence that you seem to want.
In order to save a variable that will persist after your app is destroyed, you must use some storage mechanism such as SharedPreferences or a SQLite database. For more information, you should read Storage Options in the Android Developer Guides.

Android SharedPreferences is reset to default values. After restarting app

Sometimes after restarting the app resets the sharedpreferences on devices with API level > 13.
The sharedpreferences are set at the beginning of the app (first activity of the app).
code:
Public void saveCountry(Context context, String countryCode) {
SharedPreferences settingsActivity = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settingsActivity.edit();
editor.putString("key_country", countryCode);
editor.commit();
setDefaultChannels(context);
}
public String getCountry(Context mContext) {
SharedPreferences settingsActivity = mContext.getSharedPreferences("preferences", Context.MODE_PRIVATE);
String country = settingsActivity.getString("key_country", null);
return country;
}
I dont know what im doing wrong and why it is happening. I noticed this specially after receiving a push-notification to a detailactivity.
Are you calling the saving methods at the beginning of your app like this?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
saveCountry();
Because if you are, you are calling it every time at startup, so the country will be overridden with whatever data countryCode equals at startup, which could be nothing. So maybe you should have some code that only calls that on first run.
Here is how I have it implemented in my app.
boolean firstRun;
final SharedPreferences firstRunPref = getSharedPreferences(PREFS_NAME, 0);
firstRun = firstRunPref.getBoolean("firstRun", true);
if(firstRun==true){
saveCountry();
SharedPreferences.Editor editor3 = firstRunPref.edit();
editor3.putBoolean("firstRun", false);
editor3.commit();
}

Categories