How to store values and retrieve them from sharedpreferences [duplicate] - java

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 6 years ago.
in activity1 (emailpreferences), I take the email through an edittext. I would like to use this Email again on reopenning application
This is my code:
public static final String MyPREFERENCES = "MyPref";
public static final String Email = "emailkey";
SharedPreferences sharedPreferences;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.emailpreferences);
edit1=(EditText)findViewById(R.id.editText);
buttonpref=(Button)findViewById(R.id.button);
sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
buttonpref.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = edit1.getText().toString();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Email, email);
But the email is not retrieved when the following is done:
public class MainActivity extends AppCompatActivity {
Text name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
String name = sharedPreferences.getString(Email, "email");
Toast.makeText(this,name, Toast.LENGTH_LONG).show();
}
}

Firstly, you need a commit or apply command on your editor to assign the key to the value.
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(Email, email);
editor.commit(); //or editor.apply();
PreferenceManager and SharedPreference are different. Please read on them. You retrieve the value this way.
SharedPreferences sharedPreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String name = sharedPreferences.getString(Email, "email");

To store use this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Email, email);
editor.apply();
To retrieve use this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String savedEmail = preferences.getString(Email, "email");
I would suggest you to make a utility class and create a funtion for storing and retreiving sharedPreferences so that you don't need to write this boilerplate code again and again.

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();
}
});
}
}

Trouble with shared preferences, saving a int variable

Hi I'm having trouble with sharedpreferences and saving the data of a int, I've tried everything but I can't figure it out.
Im using getExtra from two seperate activities to pull that data to the main activity and then adding those variables together to give me a total. Im trying to make it so that when leaving the main activity that all the variable stays the same and updates when the other two activites are changed.
this is the main activity with the sharedpreferences
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YearOneActivityButton();
YearTwoActivityButton();
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", MODE_PRIVATE);
scoreTotal = totalScorePref.getInt("TotalScoreY1", 0);
Intent totalGradeValueY1 = getIntent();
Intent totalGradeValueY2 = getIntent();
int year2Score = totalGradeValueY2.getIntExtra("totalYearValueY2", 0);
int year1Score = totalGradeValueY1.getIntExtra("totalYearValueY1", 0);
scoreTotal = year1Score + year2Score;
numberScore = (TextView)findViewById(R.id.number_score_txt);
numberScore.setText(String.valueOf(year1Score));
numberScore1 = (TextView)findViewById(R.id.number_score_1_txt);
numberScore1.setText(String.valueOf(year2Score));
totalGradeTxt = (TextView)findViewById(R.id.total_grade_txt);
totalGradeTxt.setText(String.valueOf(scoreTotal));
Log.d("SCORETOTAL", String.valueOf(scoreTotal));
}
#Override
public void onPause(){
int pTotalScore = scoreTotal;
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref", 0);
SharedPreferences.Editor editor = totalScorePref.edit();
editor.putInt("TotalScoreY1", pTotalScore);
editor.commit();
super.onPause();
}
}
this is how im passing the data
public void SubmitMainActivity() {
ButtonSubmit = (Button) findViewById(R.id.button_submit);
ButtonSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int totalGradeValueY1 = totalAllSpinnerValuesY1;
Intent year1ScoreIntent = new Intent(YearOneActivity.this, MainActivity.class);
year1ScoreIntent.putExtra("totalYearValueY1", totalGradeValueY1);
startActivity(year1ScoreIntent);
}
});
}
Hi please try like this
SharedPreferences topic = getSharedPreferences("topicfun", MODE_PRIVATE);
SharedPreferences.Editor topiccom = topic.edit();
topiccom.putInt("topicname",10);
topiccom.commit();
You can simply add below code after you calculate the totalGradeTxt:
SharedPreferences totalScorePref = getSharedPreferences("TotalScorePref",
MODE_PRIVATE);
SharedPreferences.Editor editor = totalScorePref
.edit()
.putInt("TotalScoreY1",pTotalScore)
.apply();
NOTE: I have used apply() instead of commit()

two SharedPreferences isn't working-java

I'm trying use two SharedPreferences, the firt is Working, but the second isn't
here is my Java Code
public class JogoActivity extends AppCompatActivity implements View.OnClickListener {
//OTHERS VARIABLES
public TextView txtViewResult,txtCoins, txtTentativas;
private static final String PREF_NAME = "JogoActivityPreferences";
int resulFinalCache,coinsFinalCache;
int count1, count2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
//methods...
//MY PROBLEMS START HERE
txtCoins = (TextView) findViewById(R.id.txtCoins);
txtViewResult = (TextView) findViewById(R.id.textViewResultado);
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1.getInt("count1", 0);
txtViewResult.setText(String.valueOf(formatter.format(count1).toString()));//THIS IS WORKING
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count2 = sp2.getInt("count2", 0);
txtCoins.setText(String.valueOf(formatter.format(count2).toString()));////THIS ISN'T
}
//Creating methods...
#Override
protected void onStop(){
super.onStop();
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
count2 = sp2.getInt("count2", 0);
editor = sp1.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences sp1= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
SharedPreferences sp2= getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS ISN'T
editor = sp2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
}
}
every time I launch the app, I use, I close the app and open again, the TextView txtViewResult is working fine, but the txtCoins isn't
I Try use just getPreferences and not getSharedPreferences, but it isn't work too
I try create other Editor, but it isn't work too
Did i do something wrong?
Thank you very much!
No need to call getsharedpreferences twice.
Just call it one time and it should be working fine.
E.g your onstop would be
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);//THIS IS WORKING
count1 = sp1.getInt("count1", 0);
SharedPreferences.Editor editor = sp1.edit();
editor.putInt("count1", resulFinalCache);
count2 = sp1.getInt("count2", 0);
editor.putInt("count2", coinsFinalCache);
editor.commit();
hmm. your solution is
SharedPreferences sp1_2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
count1 = sp1_2.getInt("count1", 0);
SharedPreferences.Editor editor = sp1_2.edit();
editor.putInt("count1", resulFinalCache);
editor.commit();
count2 = sp1_2.getInt("count2", 0);
editor = sp1_2.edit();
editor.putInt("count2", coinsFinalCache);
editor.commit();
//now both will work
infact bind the methods
Don't use the same name when getting them!
Instead of
SharedPreferences sp1 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
Use two different names like so:
SharedPreferences sp1 = getSharedPreferences(PREF_NAME1, MODE_PRIVATE);
SharedPreferences sp2 = getSharedPreferences(PREF_NAME2, MODE_PRIVATE);
Also you don't need two different shared preferences. Just use one and put those 2 values with different keys.
Generally i can advise you to use simply
For saving:
PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("name", 1).apply();
For reading:
PreferenceManager.getDefaultSharedPreferences(this).getInt("name", 0);
Enjoy!

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;
}

Categories