How to reflect changes in preferences to class? - java

I created a simple class "User" that has an attribute String username. I'm assuming that since Android uses Java, I can create custom classes and it'll use them accordingly. In my SettingsActivity.java, I have:
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_general);
SharedPreferences sharedPref = getPreferenceScreen().getSharedPreferences();
EditTextPreference editTextPref = (EditTextPreference) findPreference("username");
editTextPref.setSummary(sharedPref.getString("username", "Default"));
//sharedPref.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences arg0, String arg1) {
// Get current summary
Preference pref = findPreference(arg1);
if(pref instanceof EditTextPreference){
EditTextPreference etp = (EditTextPreference) pref;
pref.setSummary(etp.getText());
MainMenu.user.setName(etp.getText()); //This is where I try to update my class
}
}
As of right now, whenever I change the value of my EditTextPreference widget, it doesn't update the public static user object located in MainMenu. Also, a followup question - since Android saves the preferences with each instance of app launch, how would I update my User.username String on startup?

In onPostCreate remove the comment //
sharedPref.registerOnSharedPreferenceChangeListener(this);

Related

Google Maps API Reload Markers

I add Markers in the Google Map API with the following code
googleMap.addMarker(new MarkerOptions()
.position(point)
.title(text)
.snippet(textinfo)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
}
How can I make them save (I guess in onResume and in OnPause) so they will appear when i re-launch the app and not dissapear?
I don't think there is any way to automatically save the markers between launches of the map, so you either have to save the info to recreated it, or you could make use of the fact that googleMap.addMarker() returns a Marker object, and serialize that to SharedPerferences and then re-add it the next time your app launches.
See the following:
addMarker()
and
Marker
For an example of using Shared Preferences see the following link, but here is the example from the developers guide.
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();
}
}

Is there a way to hold up onSharedPreferenceChangeListener until last change?

In settings activity, I have multiple fields, once the user press save all these fields will be stored separately as key-value in sharedPreference.
The problem is every editor change e.g.
editor.putString(SERVER, server.toString());
will fire onSharedPreferenceChangeListener
While I only need to fire it after update all values..
Is there any way to achieve this requirement?
Many thanks
There's only a way to do that. You can put editor.putString(SERVER, server.toString()); in runtime code, such as you pressing a button. Once the activity gets destroyed call editor.commit(); within onDestroy() method, it will saves the value and fires onSharedPreferenceChangeListener. Simply, waiting for the user to close the activity first which means that users already changed all of their settings.
Note: please make sure that editor is an instance variable or make a field for it.
EDIT
Here's an example for you:
public class SettingsActivity extends Activity {
// a field for preference
private SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedpreferences = getSharedPreferences("MyPreference", Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
// for example, edit the value using a button at runtime
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editor.putString(SERVER, server.toString());
}
});
...
}
#Override
protected void onDestroy(){
// call commit to save all changes
editor.commit();
super.onDestroy();
}
}

can't attach an OnPreferenceChangeListener to my preferences

First of all - I have tried almoust EVERY post I could find here on stackoverflow, but none solved it for me.
I am using a begginners guide to create a simple app - hence all of the comments.
my problem is that whenever I try attaching a preference to "this" the listener (i have implemented my class as a listener: settings activity implements Preference.OnPreferenceChangeListener) my app will crash!
I'm trying to make the key of each preference it's summary.
Please help me - I've tried every relavent result and did not help. thanks alot!
This is my Settings Activity class
public class SettingsActivity extends PreferenceActivity
implements Preference.OnPreferenceChangeListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add 'general' preferences, defined in the XML file
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Fragment1 fragment1 = new Fragment1();
ft.replace(android.R.id.content, fragment1);
ft.commit();
// For all preferences, attach an OnPreferenceChangeListener so the UI summary can be
// updated when the preference changes.
**Here I need to somehow attach the preferences to the listener - but I can't seem to do it without the app crashing**
}
/**
* Attaches a listener so the summary is always updated with the preference value.
* Also fires the listener once, to initialize the summary (so it shows up before the value
* is changed.)
*/
private void bindPreferenceSummaryToValue(Preference preference) {
// Set the listener to watch for value changes.
//preference.setOnPreferenceChangeListener(this);
// Trigger the listener immediately with the preference's
// current value.
onPreferenceChange(preference,
PreferenceManager
.getDefaultSharedPreferences(preference.getContext())
.getString(preference.getKey(), ""));
}
#Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list (since they have separate labels/values).
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
preference.setSummary(listPreference.getEntries()[prefIndex]);
}
} else {
// For other preferences, set the summary to the value's simple string representation.
preference.setSummary(stringValue);
}
return true;
}
}
If you want to set the current preference value to it's summary, just add in your preference.xml
android:summary="%s"
now you dont nead the listener
You have to do that in onResume() and onPause() as described in this document: http://developer.android.com/guide/topics/ui/settings.html
Just search for onResume in it.
I use this in my App and its works without Problem
Have a try, maybe it works
public class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
//....... Code
}
Android Settings Guide

Android boolean preference problem

I want to have the status of a checkbox be saved into my prefs.
I set a listener on the checkbox, and if it is checked I do a prefs.putBoolean("cbstatus", true), and it is it unchecked i do a prefs.putBoolean("cbstatus", false);
Trouble is, in my onStart() when I get prefs, my Boolean getcbstatus = prefs.getBoolean("cbstatus", false); will always return a true, regardless of how my listener should have set that status previously.
What am I doing wrong? I have working prefs for other things like spinners, textviews, and edit texts, but what should be the simplest type (a boolean) is giving me a hard time.
I've even tried taking out all code related to listeners and pref setting for this checkbox, so that the only code in the entire activity that deals with the checkbox is in the line
Boolean getcbstat = prefs.getBoolean("cbon", false);
if (getcbstat = true) {
cb1.setChecked(true);
}
else {
cb1.setChecked(false);
format.setVisibility(View.VISIBLE);
}
Since there is no cbon preference (i deleted them all), it should return false by default and the box should be unchecked since. cb1, of course, is the name of my checkbox.
Any ideas?
Update on the code:
OnClickListener cb = new OnClickListener() {
public void onClick(View v) {
if (cb1.isChecked()) {
prefs.putBoolean("cbon", true);
}
else {
prefs.putBoolean("cbon", false);
}
}
};
And in the onStart():
Boolean getcbstat = prefs.getBoolean("cbon", false);
cb1.setChecked(getcbstat);
You've accidentally assigned it to true in your if statement.
Change it to this
if (getcbstat == true)
[Edit -- How to use shared preferences (instead of Java's preferences class)]
How to use SharedPreferences:
private SharedPreferences mPref;
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
mPref = getSharedPreferences("my_prefs_file", MODE_PRIVATE);
//Other onCreate code goes here...
}
//Example of where you might want to save preferences
#Override
protected void onPause() {
super.onPause();
Editor prefEdit = pref.edit();
prefEdit.putBoolean("cbon", true);
prefEdit.commit();
}
When you need to read it later:
//Example of where you might want to save preferences
#Override
protected void onResume() {
super.onResume();
boolean getcbstat = pref.getBoolean("cbon", false);
}
It would probably be a good idea to make the pref variable class level and get the preferences object in the onCreate section. Change "my_prefs_file" to whatever you like, but remember that that string is what you will use to access that that particular set of preferences from within your application. I also recommend using constants instead of raw strings for the access keys (like "cbon").
Good luck:)

Saving and restoring state in android

I have searched through this and a few other sites for the answer, but I have been unable to find it. I am trying to save a boolean and an int using onSaveInstanceState and onRestoreInstanceState, but I can't seem to get it to work. It doesn't crash or anything, but it either isn't saving it or it isn't restoring it, or I am stupid and have no idea what I am doing.
Here is what I have for my activity, do I need to have it in my onCreate somewhere or something?
public class CannonBlast extends Activity {
/** Called when the activity is first created. */
private panel panelStuffz;
#Override
public void onCreate(Bundle savedInstanceState) {
final Window win = getWindow();
super.onCreate(savedInstanceState);
panelStuffz = new panel(this);
requestWindowFeature(Window.FEATURE_NO_TITLE);
win.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(panelStuffz);
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState){
savedInstanceState.putInt("HighLevel", panelStuffz.getLevel());
savedInstanceState.putBoolean("soundstate", panelStuffz.getSound());
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
panelStuffz.setHighLevel(savedInstanceState.getInt("HighLevel"));
panelStuffz.setSound(savedInstanceState.getBoolean("soundstate"));
}
#Override
public void onResume(){
super.onResume();
}
#Override
public void onPause(){
super.onPause();
panelStuffz.setThread(null);
}
#Override
public void onStop(){
}
I tried putting stuff in the onStop, but it crashes, which is why its empty, in case that matters, thanks in advance
Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.
Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.
Shared Preferences: The shared preferences can be used by all the components (activities, services etc) off the applications.
Activity handled preferences: These preferences can only be used with in the activity and can not be used by other components of the application.
Shared Preferences:
The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file(1) or you can specify a file name(2) to be used to refer to the preferences.
(1) Here is how you get the instance when you specify the file name
public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);
MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two mode supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.
(2) The recommended way is to use by the default mode, without specifying the file name
SharedPreferences preferences = PreferencesManager.getDefaultSharedPreferences(context);
Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:
int storedPreference = preferences.getInt("storedInt", 0);
To store values in the preference file SharedPreference.Editor object has to be used. Editor is the nested interface of the SharedPreference class.
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
Editor also support methods like remove() and clear() to delete the preference value from the file.
Activity Preferences:
The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activities private preferences. You can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.
Following is the code to get preferences
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);
The code to store values is also same as in case of shared preferences.
SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();
You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.
To see some more examples check Android's Data Storage post on developers site.
This method is only for saving state associated with a current instance of an Activity,are you switching to another activity and trying to get the values again when you return to this activity? i supposed that :: "I tried putting stuff in the onStop, but it crashes".
a recommendation, is NOT SAFE to use onSaveInstanceState() and onRestoreInstanceState(), according to http://developer.android.com/reference/android/app/Activity.html
consider using Sharedpreferences or SQLite database.
SharedPreferences Example (from webworld):
/**
* get if this is the first run
*
* #return returns true, if this is the first run
*/
public boolean getFirstRun() {
return mPrefs.getBoolean("firstRun", true);
}
/**
* store the first run
*/
public void setRunned() {
SharedPreferences.Editor edit = mPrefs.edit();
edit.putBoolean("firstRun", false);
edit.commit();
}
SharedPreferences mPrefs;
/**
* setting up preferences storage
*/
public void firstRunPreferences() {
Context mContext = this.getApplicationContext();
mPrefs = mContext.getSharedPreferences("myAppPrefs", 0); //0 = mode private. only this app can read these preferences
}

Categories