I have multiple views that come and go as the application runs. I want each view to have its own personal preferences that are stored as the ID tag of the view. Above these is the "General Preferences" that the sub prefs reference to get their default values when a view it is created.
Right now I have it set up that the General Preferences are the default SharedPreferences. But I have no Idea how to create the new preferences and set up an activity UI so the user can change them. Is it pretty much the same as setting up the SharedPreferences?
this may not be exactly what you're asking for, but here's what I do:
in my main activity, when I call the preferences activity, I pass it the name of the custom preference file as extra data in the intent:
static final String EXTRA_PREFERENCES_NAME = "android.intent.extra.PREFERENCES_NAME";
...
Intent intent = new Intent(this, Preferences.class);
intent.putExtra(EXTRA_PREFERENCES_NAME, preferencesName);
startActivity(intent);
then, in my preferences activity, I get the custom preferences name and set it like this:
public class Preferences extends PreferenceActivity {
private String preferencesName = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get the custom preferences name from the extra data in the intent
preferencesName = getIntent().getExtras().getString(MainActivity.EXTRA_PREFERENCES_NAME);
// set the preferences file name
getPreferenceManager().setSharedPreferencesName(preferencesName);
// get the default preferences from XML
addPreferencesFromResource(R.xml.preferences);
}
lastly, in my main activity, I get specific preferences like this:
SharedPreferences preferences = getSharedPreferences(preferencesName, MODE_PRIVATE);
String somePreference = preferences.getString("somePreference", defaultValue);
Somehow I am not worthy to comment but to write an answer, so here we go:
I'd really like to know how to use sharedPreferences with PreferencesActivity instead of DefaultSharedPreferences.
One way I can think of to accomplish this is letting the preferenceActivity save the values to defaultSharedPreferences and then read these values out and save them into a sharedPreferences associated with a name that would match the kind of values saved.
But this seems very wrong. So how do you guys do this? Or do you save all your values from any PreferencesActivties into defaultSharedPreferences?
You can use PreferenceManager to achieve the objective.
Related
I have one Textbox in Main activity and one edit textbox in Create Activity. I used the create activity to generate my text to the textbox in main activity. This part works.
However, when i switched back to create activity, the text in texbox in main activity is gone.
I want to save the text in textbox even after switching activities
Have a look at SharedPreferences to save the value of your String across the activities.
In MainActivity, read from the SharedPreferences. Get the String value from the SharedPreferences (default value is set to be the String "Default Value") and set that value to the TextView.
SharedPreferences sharedPreferences = getSharedPreferences("sharedPrefs", MODE_PRIVATE);
// read from SharedPreferences
// get the string value using the key "string" set when writing to the shared preferences
// return string default otherwise
String string = sharedPreferences.getString("string", "Default Value");
// get the TextView
TextView textView = (TextView) findViewById(R.id.textView);
// setText on TextView
textView.setText(string);
In CreateActivity, write to the SharedPreferences. In the lifecycle method onPause() of your activity, write to the SharedPreferences by getting the value from the EditText using the getText() method.
#Override
protected void onPause() {
super.onPause();
// write to SharedPreferences with edit
getSharedPreferences("sharedPrefs", MODE_PRIVATE).edit()
.putString("string", editText.getText().toString())
.apply();
}
Quick note: When getting SharedPreferences using getSharedPreferences(), be sure to use the same name - in our case "sharedPrefs".
Tried and tested just now - so feel free to ask questions!
There are some project for you:
1.Make the text as cache, and when you switch to main activity, you take the text from cache and set text to the textbox, you can use SharePrefrence or DiskCache to save the cache
2.make main activity Single, like set the launchMode="singleTask" in AndroidManifest.xml ,you should make that main activity would not be finish when you switch to create activity
There are my idea, you can try, good luck!
I would like the user to be able to create a nickname for a string that shows up in their textview. The app will feed a string into the activity through a service and display it in a textview. I would then like the user to be able to nickname that string, so that every time the string is displayed again the nickname will show up instead of the original string.
My question is, can I use shared preferences to do this? What would be the logic behind the user being able to assign nicknames? If you could point out any literature or sample code that would be greatly appreciated as well. Thank you for any help.
Algorhithm:
At a certain point in your app lifecycle, write a preference using a "name" and a value.
Retrieve the value when the app starts and compare it to something.
Act consequently.
From the reference site: http://developer.android.com/guide/topics/data/data-storage.html#pref
Using Shared Preferences
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).
User Preferences
Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, see PreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).
To get a SharedPreferences object for your application, use one of two methods:
getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
To write values:
Call edit() to get a SharedPreferences.Editor.
Add values with methods such as putBoolean() and putString().
Commit the new values with commit()
To read values, use SharedPreferences methods such as getBoolean() and getString().
Here is an example that saves a preference for silent keypress mode in a calculator:
public class Calc extends Activity
{
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
//...
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getBoolean("silentMode", false);
setSilent(silent);
}
#Override
protected void onStop()
{
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
I want to display the server response on multiple screen in header bar in Android? Please, tell me how to do that? I created an abstract class and defined the Asynctask class. In onPostExecute method i am using the textview for displaying the result. Now my question is how all the activities access this textview?
I am new with Android. Please, give me the proper way to solve this?
May be you can use the shared preference feature of android to save the response.
References are How to use SharedPreferences in Android to store, fetch and edit values and http://www.vogella.com/tutorials/AndroidFileBasedPersistence/article.html
On each activity, you can set the header by referring the value from shared preference.
Create one base activity and extend that created base activity instead of activity. Create one xml file in base activity, in it only declare your header. nothing else, now to display use that xml and for the other contents you can use your actual xml file. So this one is for to set global header. Now, save your response to Shared preferences and use it throughout the app whenever you need.
Store the value into Shared preferences
SharedPreferences sharedPref = context.getSharedPreferences("app_prefs", Context.MODE_PRIVATE);
// saving
sharedPref.edit().putString("key", "value").commit();
// reading
sharedPref.getString("key", "default");
You need to store the response values in Stringbuffer
StringBuffer value =new StringBuffer("your response value");
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("Identifier",value);
editor.commit(); //important, otherwise it wouldn't save.
Get the value in next activity
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
final String myVariable = prefs.getString("Identifier", "value");
My first attempt at preferences was without knowledge of PreferenceActivity. So now I have an app that stores all user preferences in a specific preference file.
I want to migrate to using a PreferenceActivity but I also want my users to keep their preferences.
Is there a way to tell my PreferenceActivity to use that specific file for all preferences?
It may be too late to post this but you can find a nice solution here
How to make PreferenceActivity use non-default SharedPreferences
You set the name of the default shared preferences file beforehand like this:
public class MyPreferencesActivity extends PreferenceActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PreferenceManager prefMgr = getPreferenceManager();
prefMgr.setSharedPreferencesName("my_preferences");
prefMgr.setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.preferences);
}
}
I hope this helps somebody.
Regards.
You could read all the preferences at the beginning of your app, and then store them in the Preferences using
Editor e = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).edit();
e.putBoolean("yourPreference", true);
e.putString("yourOtherPreference", "This is the Value");
...
e.commit();
I hope that helps
Maaalte is correct, what you want to do is onCreate test for the existence of your custom file and if it's there, rename it to standard shared preferences filename.
Another option is to read your old prefs one-by-one and use the shared preferences API to add them as you read them and then delete your old prefs when you are done.
Currently, I'm using the following code across all of my activities in my app to store application level variables and carry values between activities..
prefs = this.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
I didn't have a PreferenceActivity prior to this, but now I do and I am looking to store a few user prefs from this new PreferenceActivity in the same sharedPreferences tag, "MyPrefs".
I know I can access the PreferenceActivity SharedPrefs from my activities via
prefs = PreferenceManager.getDefaultSharedPreferences(this);
but I would like those values saved to my current sharedPreferences tag, "MyPrefs", but I'm not sure how to do this.
Thanks in advance..
You can change the default name of SharedPreferences file used by PreferenceActivity.
I did this in onCreate method of PreferenceActivity by adding the following piece of code:
getPreferenceManager().setSharedPreferencesName("MyPrefs");
Yes, you can http://idlesun.wordpress.com/2011/04/08/how-to-make-preferenceactivity-use-non-default-sharedpreferences/
You can't. the PreferneceManager always uses this.getPackageName () + "_preferences as preference name. Sorry to break the bad news. This is also important when you wish to use the new backup framework.
You can of course replace MyPrefs with this.getPackageName () + "_preferences.