my activity has a string which gets its value from an intent
String myString = intent.getStringExtra("KEY");
in this activity I start another activity. From the new activity I want to return to the previous activity and still have the same value of myString. But when I open a the new activity the value of myString is deleted.
i looked into onSavedInstancState but that doesn't seem to work.
making myString static works but I think that this is not good programming.
So what would be the best way of doing this?
Use ShareDPreferences to store an object that you want to retrieve later:
SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("key", ""KEY");
editor.commit();
To retrieve it later:
pref.getString("key", null);
You can use SharedPreferences,
If you have a relatively small collection of key-values that you'd
like to save, you should use the SharedPreferences APIs.
Related
I'm using SharedPreferences to save username but it's not working.
In login Activity (read):
ocUserName = (EditText)findViewById(R.id.userNameText);
SharedPreferences prefs = this.getPreferences(Context.MODE_PRIVATE);
String userNameKey = "userName";
String userNameTV = prefs.getString(userNameKey,null);
SharedPreferences.Editor editor = prefs.edit();
if(userNameTV != null) {
ocUserName.setText(userNameTV);
}
in second Activity (write):
SharedPreferences prefs =
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
String userNameKey = "userName";
editor.putString(userNameKey, ocUser);
editor.commit();
Activity.getPreferences(int mode) (as used in your login activity) has a comment:
Retrieve a {#link SharedPreferences} object for accessing preferences that are private to this activity.
In your second activity you use Activity.getSharedPreferences(String name, int mode) and provide what looks like your Application Id as the name.
In effect, you are using two different sets of shared preferences in each activity.
I recommend using PreferenceManager.getDefaultSharedPreferences(Context context) if you intend to use the shared preferences throughout your application.
I assume the problem is that you are unable to read the written value. You need to use the same file in login activity:
SharedPreferences prefs = this.getSharedPreferences("com.mesbahsoft.IRIB", Context.MODE_PRIVATE);
If this does not work, kindly specify clearly where you are seeing the problem and also specify exceptions seen.
You are accessing different shared preferences in your activities,
this.getPreferences( Context.MODE_PRIVATE); is shorthand for this.getSharedPreferences( <activity's class name>, Context.MODE_PRIVATE);
In you login activity, use this,
getSharedPreferences("com.mesbahsoft.IRIB", MODE_PRIVATE);
References:
http://developer.android.com/reference/android/app/Activity.html#getPreferences(int)
http://developer.android.com/reference/android/content/Context.html#getSharedPreferences(java.lang.String,int)
I need to send data Date Display to next Activity and keep that data
private void updateDisplay()
{
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(ShowdatanameActivity.this);
SharedPreferences.Editor editor = app_preferences.edit();
mDateDisplay.setText(new StringBuilder().append(mMonth + 1).append("-").append(mDay).append("-").append(mYear).append(" "));
editor.putString("key1", mDateDisplay);
editor.commit();
Intent myIntent = new Intent(ShowdatanameActivity.this,Showdata_result_resume.class);
startActivity(myIntent);
}
Well that's true you can acces to Data/Calendar object from every place of your application. But if you insist:
You've put your string to SharedPreferences under "key1" so in other activity you have to call:
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences("KEY_FOR_YOUR_DATA",ShowdatanameActivity.this);
String data = app_preferences.getString("key1","");
So when you call SharedPreferences you also need key for them. It's some kind of "database version", you can write anything there (i use for example PREFS-KEYv1, and when I need new one I'm incrementing to v2). And don't use same key everywhere it's bad practice.
The other method you could use to send your String to other activity is via intent.
intent.putExtra("key1",yourStringVariable);
and Showdata_result_resume in onCreate after setContent you can get it by:
String data = intent.getExtras().getString("key1");
Using code like this to make preferences code portable between various apps and classes.
from a fragment I get the sharedpref like this. Notice how I have the preferences named in a resource and I use getActivity to get to the preferences.
sharedPref = getActivity().getSharedPreferences(
getString(R.string.preferences), Context.MODE_PRIVATE);
From the main activity I get the sharedpref like this. Notice how I have the preferences named in a resource.
sharedPref = getSharedPreferences(getString(R.string.preferences),
Context.MODE_PRIVATE);
the resource which is shared by all classes in the app.
<string name="preferences">com.gosylvester.hilbilyfashliegt.prefrences</string>
<string name="about_firstrun">com.gosylvester.hilbilyfashliegt.firstrunabout</string>
now to get the data from any class I referer to it with an R string resource.
_Checked = sharedPref.getBoolean(getString(R.string.about_firstrun),
false);
Good Luck
I'm creating a SharedPreferences and it's working only if I start Activity like this:
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
But my SharedPreferences is not working after I save it and hit back a few times, to go at menu page and go to the page where I want to get my preferences.
Anyone can help me with that?
Code below:
This is where I save my preferences:
String MYPREFS = "MyPref";
SharedPreferences mySharedPreferences;
SharedPreferences.Editor myEditor;
Inside onCreate:
mySharedPreferences = getSharedPreferences(MYPREFS,0);
myEditor = mySharedPreferences.edit();
Inside button onClickListener:
myEditor.putString("address", AddressET.getText().toString());
myEditor.putString("contact", ContactET.getText().toString());
myEditor.commit();
Intent myIntent = new Intent(myContext, nok_individual_particular.class);
myIntent.putExtra("prefName", MYPREFS);
startActivity(myIntent);
This is the activity I pass to:
SharedPreferences mySharedPreferences;
Inside onCreate:
Intent myReceivingIntent = getIntent();
String myPREFName = myReceivingIntent.getStringExtra("prefName");
mySharedPreferences = getSharedPreferences(myPREFName, 0);
applySavedPreferences();
In the applySavedPreferences method:
String addressValue = mySharedPreferences.getString("address", "Jack Smith");
String contactValue = mySharedPreferences.getString("contact", "Jack Smith");
addressTV.setText(addressValue);
contactTV.setText(contactValue);
SharedPreferences: This is how it works
To save your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
SharedPreferences.Editor editor = sPrefs.edit();
editor.putString("valueName", "value");
editor.commit();
To retrieve your data:
SharedPreferences sPrefs = getSharedPreferences("prefsName", 0);
String strMyData = sPrefs.getString("valueName", "default value");
The example above is how to set a string and retrieve it.
You are not using SharedPreferences. In your example, you are passing an extra to an activity, but this only makes available the value to the new activity, it doesn't save the value to SharedPreferences.
To use SharedPreferences, you have to do the following:
Save
PreferenceManager.getDefaultSharedPreferences(this).edit().putString("prefName", "String to save").commit();
Get
String value = PreferenceManager.getDefaultSharedPreferences(this).getString("prefName"), "default value");
After mySharedPreferences.edit();
mySharedPreferences.commit();
should be your last line. This enables u to save and close the SharedPreferences file you have edited.
Well, you don't need to pass the sharedprefs in an intent and all. It will be available throughout your application in all activities.
Just call SharedPreferences my_prefs= getSharedPreferences("Pref_name", 0); and then u have a reference to that SharedPreferences file and then u can retrieve values from it.
I prefer using SharedPreferences to save my data and use it throughout my classes , plus they will be saved to the device , making them available even after the app is killed ... Here is an example for ya !
//Some String that I should remember, I am just using the package name for now
String app = this.getPackageName();/*This is going to be used more like a file to save my stuff to*/
//Setting our sharedpreferences
SharedPreferences sha = sha = getApplicationContext().getSharedPreferences(app, SherlockActivity.MODE_PRIVATE);
String myString = "This is the String that you want to save so you can use among your classes"
//Now we call in an editor for that SharedPreferences so we can write and delete stuff from it .
Editor edit = sha.edit();
//Now we insert our String.
edit.putString("Something_you_can_remember" , myString);//You will need the "Something_you_can_remember" a few lines ahead , so remember it !
edit.apply(); //Or we can use edit.commit() , but I prefer apply()
//Now our String is saved ! So lets read it !
String whatever = sha.getString("Something_you_can_remember" , "The String incase myString didn't even exist , saves you from a NullPointerException");
//Here we go ! Now we have our String saved and can be readable among the classes !
//Also , if you wanted to delete that String or whatever you "put" in there , you can call
edit.remove("Something_you_can_remember"); //or edit.clear() to remove all the values stored !
Hope this helps !
Save
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("valueName", "String to save");
sedt.commit();
Get
SharedPreferences sp = getSharedPreferences("key", 0);
String valueName = sp.getString("valueName","");
You do not need to pass SharedPrefences through intents, as SharedPreferences are available to the whole application and any activity has access to it.
You can refer to below example:
Either create SharedPreferences by giving them your choice of name:
SharedPreferences pref = getSharedPreferences("MyPref", MODE_PRIVATE);
OR use default SharedPreferences:
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
Use your preference file anywhere in your code by getting them through any of the above methods. No need to pass to different activities.
Once you call any of the above method, if the preference file of that name does not exist for your application, android will create one for you.
I want to store and retrieve data that is accessible to all activities in my app using SharedPreferences. Is that possible? Up until now I have been doing it such that the data is stored for a particular activity.
Yes. SharePreferences do exactly this.
In every activity you can this:
SharedPreferences prefs = getSharedPreferences(ApplicationConstants.PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(name, value);
editor.commit();
And then retrieve values in other activty doing this:
mPrefs.getString(name, "");
This is the documentation:
http://developer.android.com/reference/android/content/SharedPreferences.html
And this is a good example to start with:
http://myandroidsolutions.blogspot.it/2012/03/android-preferenceactivity.html
Yes, that's the whole purpose of it.
Here's how you should write to it, via Editor
final SharedPreferences shp = ctx.getSharedPreferences(ctx.getString(R.string.app_name), Context.MODE_PRIVATE);
final SharedPreferences.Editor ed = shp.edit();
ed.putString("var1", "var1");
ed.putString("var2", "var2");
And to load it:
shp.getString("var1", "defvalue");
I have a better version. As sometimes when you try to do getSharedPreferences you might get an error as it could not be found.
This is how I store values in my Android projects.
Add
SharedPreferences sharedPreferences=this.getSharedPreferences("packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("username", "specify name here").apply();
Package Name can be directly copied from top of the activity ex: com.example.name.projectname
Retrieve
String username = sharedPreferences.getString("username","");
If you want to access values in all of your activities I think the better way is storing in a custom Application class and later in activities you can:
((CustomApplication)getApplication()).getStoredValue()
Shared preferences are stored in files and this file access is slower.
Is my example for create function for set and get an object data called "USER"
For set sharePreference data
public void saveUser(User usuario) {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", usuario.getNombre());
editor.putString("username", usuario.getUsername());
editor.putString("pass", usuario.getContrasena());
editor.putString("roll",usuario.getRol());
editor.commit();
}
For get sharePreference data
public Usuario getUser() {
SharedPreferences sharedPref = getSharedPreferences("A", Context.MODE_PRIVATE); // sharedpreference set named "A"
User usuario = new User();
usuario.setNombre(sharedPref.getString("name", "null"));
usuario.setUsername(sharedPref.getString("username", "null"));
usuario.setContrasena(sharedPref.getString("pass", "null"));
usuario.setRol(sharedPref.getString("roll", "null"));
return usuario;
}
Important: set name to sharePreference in this case "A"
I am trying to save a date in one activity and then have that date put in a textView in another activity. I am not sure about how to get the two activities to communicate with each other.
In file called report.java I have this method that gets the date and save it in sharedPrefernces.
private void updateLabel() {
date.setText(fmtDate.format(dateAndTime.getTime()));
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("date", date.getText().toString()); // value to store
editor.commit();
}
I am trying to figure out how to get my file called inspection use this to populate a textView
The problem I think I am having is with getting the correct name for the report file.
public static final String PREF_FILE_NAME = "report";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
then I have this code on a method called onResume()
#Override
public void onResume() {
super.onResume();
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String strDate=preferences.getString("date", date.getText().toString());
date.setText(strDate);
}
You are saving the value to two seperate preference files.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
Use only one.
Why not use the default preference file that is accessible by all classes/activities of your app?
SharedPreferences preference = PreferenceManager.getDefaultSharedPreferences(yourContext);
preferences.edit().putString(YOURKEY, yourStrValue);
This way you are not creating extra preference files in your app that you have to remember which values are stored in which files. Definately makes life easier.