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.
Related
Very strange issue - I'm using the latest version of Android Development. Here is my code:
public static final String MY_PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
Set<String> savedCityFare = editor.getStringSet(whatever);
Funny part is none of the getter methods are available for editor. What am I doing wrong?
If you take a look at the documentation at http://developer.android.com/reference/android/content/SharedPreferences.Editor.html you'll see that the SharedPreferences.Editor class only has putX() methods defined. If you want to use the getters, you don't need an Editor but only a SharedPreferences object.
SharedPreferences preferences = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Set<String> savedCityFare = preferences.getStringSet(whatever);
I would also suggest using PreferenceManager.getDefaultSharedPreferences() to obtain a SharedPreferences object.
JUST AN EDIT
To add value in SharedPreferences:
PreferenceManager.getDefaultSharedPreferences(YOUR_CONTEXT).edit().putXXX(YOURKEY,YOURVALUE).commit();//This will directly save value in your SharedPreferences.
When you want to fetch the value from your Preferences:
PreferenceManager.getDefaultSharedPreferences(YOUR_CONTEXT).getXXX(YOUR_KEY);//THIS WILL Returned you the stored value.
Default Preferences are used when you want to maintain a single instance of SharedPreferences throughout the app.
Funny part is none of the getter methods are available for editor
The getter methods are on the SharedPreferences. Only the setter methods are on the SharedPreferences.Editor. Think of the SharedPreferences.Editor as being a builder-style class for creating and executing a "transaction" to update the shared preferences.
I have a fragment where I let set some SharedPreference values set.
In the fragment, everything works fine - I can get any value I want, saving, editing, deleting works fine.
Then I have an Activity, from where I want to get the value "savedValue1" - but it does not work
public static final String MyPref = "MyPreference";
static SharedPreferences sharedpreferences;
//onCreateView...
sharedpreferences = this.getActivity().getSharedPreferences(MyPref,
Context.MODE_PRIVATE);
editor.putString("savedValue1", someString);
editor.commit();
I tried it with in Fragment:
public static String getValue(){
return sharedpreferences.getString("savedValue1","");
}
in Activity:
String newValue = Fragment.getValue();
But that doesn't work - any hint?
You should not have a Fragment.getValue() method.
SharedPreferences are here to avoid that.
Use the same getSharedPreferences("whatever", Context.MODE_PRIVATE) code and you shall get/set the same values inside the same preferences.
That is how it is supposed to be used. From the official documentation:
For any particular set of preferences, there is a single instance of
this class that all clients share.
Use this code to save and retrieve values from SharedPreferences
//To save string
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor e = settings.edit();
e.putString("savedValue1", someString);
e.commit();
//Retrieve team score
String saved_value = settings.getString("savedValue1", "");
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)
my app crashes with a null pointer exception on the code below.
i have an xml preference file under res/xml/defaults.xml
Any idea why it's crashing?
public class Preference extends Activity {
public Preference()
{
}
public String getPreference(String key)
{
//it still crashes here
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
String result = settings.getString(key, null);
return result;
}
}
Preference files are not storead in project's /res/xml/defaults.xml
They are stored on the device in your application folder something like
/data/data/com.your.pkg/default.prefs
Try do not specify the file name, as you will have some problems with the preference files, like this OP had here
SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(context);
Then you will probably have to query
preferences.getString('weightPref', null);
Here's a sample code which shows how to save and retrieve Preferences. Here I am saving username and password in SharedPreferences.
SharedPreferences uPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE);
SharedPreferences.Editor editor; = uPreferences.edit(); //Instantiating editor object
protected void storeSharedPrefs(String username, String password) {
/*
* Storing in Shared Preferences
*/
editor.putString("username", username);
editor.putString("password", password);
editor.commit(); //Commiting changes
}
Retrieving username and password in another activity from SharedPreferences.
private SharedPreferences mSP;
mSP = getSharedPreferences("CurrentUser", MODE_PRIVATE);
String username = mSP.getString("username", null);
String password = mSP.getString("password", null);
Hope it helps..
Setting a value in the shared preferences:
Editor prefs = getSharedPreferences("Application_name", MODE_PRIVATE).edit();
prefs.putString("key", accountKey);
prefs.commit();
Getting the value from another activity:
String accountKey =
this.getSharedPreferences("Application_name", MODE_PRIVATE).
getString("key", null);
It would be nice if you access the variable by using some predefined handler, such as getString(R.string._key), instead of the hardcoded string "key".
Your Preferences should extend PreferenceActivity. Then you need to create a resource xml file for preferences, and reference that in your PreferenceActivity like so:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
etc.
}
The preferences xml should have a PreferenceScreen as the top level element, and you can take advantage of all the different preference views Android makes available to you for setting preferences. This would be the most common, and elegant way to do it.
I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?
I assume by preferences you are referring to your application's preferences and not Android phone settings.
To store preferences between runs of you application you need to do the following
Create a SharedPreferences object
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
String n identifies your preferences and the second argument is the mode they'll be accessed
Instantiate an Editor object
SharedPreferences.Editor editor = settings.edit();
Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work
Write your preferences to the buffer
editor.put...(String, value)
There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)
Flush the buffer
editor.commit();
This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.
These preferences will by stored on the phone and will only be accessible to your application.
More documentation is here
I tried this but didn't work:
SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
Try this instead:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
You can save something in the sharedpreferences by using below code
public static void save(String valueKey, String value) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
SharedPreferences.Editor edit = prefs.edit();
edit.putString(valueKey, value);
edit.commit();
}
To read preferences:
public static String read(String valueKey, String valueDefault) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
return prefs.getString(valueKey, valueDefault);
}