Using SharedPreferences to store and retrieve int - java

This is driving me crazy. Cannot seem to get this to work at all. I'm pretty inexperienced so any tips would be grand. I hope it is just a stupid mistake that someone can explain.
A number is derived in one class. The number is then used within that class without a problem. Within that Class I store that number using the shared preferences method. However in a later Class when I attempt to retrieve that number the app crashes out.
This is the class where I process and try to store the number:
public class Summary extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
int Time = gotTime();
// Create object of SharedPreferences.
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(Summary.this);
//now get Editor
SharedPreferences.Editor editor = sharedPref.edit();
//put your value
editor.putInt("TargetTime", Time);
//commits your edits
editor.
// I then display the Time on that screen which all works ok
TextView textViewT = (TextView) findViewById(R.id.textView4);
textViewT.setText("Time is " + Time);
};
public int gotTime(){
//do stuff to generate the value for time stored as variable PenileTim
return PenileTim;
};
}
Then in a future class I try to retrieve the Time:
public class Map extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
int VarTime = sharedPref.getInt("TargetTime", (Integer) null);
TextView textViewP = (TextView) findViewById(R.id.textTest);
textViewP.setText(" " + VarTime );
}
}
Anybody have any idea what is going wrong?

Related

Problem to remove a backup - ANDROID STUDIO

Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
Little problem in my learning.
Sorry for my frenchglish ^^
A variable changes every time, i press a button, it backs up and assigns it ++.
In the button input if the variable == in table REPONSE.Length, It restarts the activity and it REMOVE the backup.
My problem is that the backup does not remove itself while the activity restarts well.
Every time i support the activity it raises again without being able to start again at stage 0.
int REPONSE[]= new int[5]; //tableau des reponses
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
Question = sharedPreferences.getInt("num", 0);
cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.apply();
Intent intent1 = new Intent(Questions.this, Questions.class);
startActivity(intent1);
}
//Sauvegarde de la variable
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("num", Question++);
editor.apply();
//Incrementation +1
Question++;
}
}); }
Thanks in advance:)
According to the documentation remove() removes a value once commit() is called. So you have to change editor.apply() to editor.commit()
//Restart si Question == REPONSE.length
if (Question == REPONSE.length){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("num");
editor.commit(); //editor.apply() won't work
There are 3 points that I wold recommend you:
Point 1:
Try giving your Shared preference a name. Example:
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
If you are not giving a name to the shared preference android can fall into ambiguity and create a new Sharedpreference thus not affecting the old one.
Even you are creating a new SharedPreference inside the onClick method(this process is wrong), and there the android system is not being able to understand which Shared Preference to use thus not affecting the sharedpreference data that you want to change.
Point 2:
This not so important as the first one but to change the data of an already existing preference you need not to delete the preference instead just change the value, and it will be updated to your requirement:
sharedPreferences.edit().putInt("num", Question++).apply();
Point 3:
Create SharedPreference object once inside the class where it can
have global scope.
Initialize the SharedPreference only once in an activity inside
onCreate method.
Make your code something like this:
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
ConstraintLayout layout;
int Question = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
layout = findViewById(R.id.layout);
sharedPreferences = getSharedPreferences("sharedPrefName", MODE_PRIVATE);
Question = sharedPreferences.getInt("num",0);
layout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sharedPreferences.edit().putInt("num", Question++).apply();
}
});
}
}

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

Android App - sharedpreferences not loading properly

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.

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