I am making an application that contains a form and whenever a data clicks a button loads from a BD in a EditText, but every time I press a different button, the other EditText are cleared, I tried with:
#Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putString("data", myVariable);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
other = savedInstanceState.getString("data");
name.setText(other);
}
Sorry if I have not explained well, I need that every time they change Activity variables and I have not deleted. Any suggestions? Thank you!
Try using Android SharedPreferences instead. This is a persistent key-value storage that Android offers for its apps and was designed to covers issues like this. Here's the easy way to use it:
SharedPreference prefs = PreferenceManager.getDefaultSharedPreferences(this);
// To put a data (in this case a String from your EditText)..
Editor editor = prefs.edit();
editor.putString("data", yourStringHere);
editor.commit();
...
// ..and to retrieve it..
prefs.getString("data", null);
// NOTE: The 'null' in above method call could be replaced by any String you want;
// it basically specifies a default value to get when "data" is empty or doesn't
// yet exist.
Hope this helps.
Related
Order of calls according to logcat is onCreate, setViewValues, setStrikethroughFlag, (ROTATE), onCreate, setViewValues:
SharedPreferences mSettings;
Editor spEditor;
#Override
public void onCreate(Bundle savedInstanceState) {
....
mSettings = getSharedPreferences("prefs", "")
spEditor = mSettings.edit();
setViewValues();
}
public void setViewValues() {
boolean isStrikeThru = mSettings.getBoolean(STRIKETHROUGH, false);
Log.d("TRACE", "setViewValues, strikethrough " + isStrikeThru);
}
public void setStrikethroughFlag() {
spEditor.putBoolean(STRIKETHROUGH, true);
spEditor.commit();
}
The logcat says setStrikethroughFlag() is called. Then I rotate the screen, onCreate and setViewValues are called. In setViewValues, I thought it would recognize the saved value of STRIKETHROUGH, true. But the logcat trace says the value of isStrikeThru is false.
Try calling the setViewValues() from the Constructor. In Screen orientation change, the oncreate of the activity will gets called again and resets your values.
From know i can see, that you creating local variable in your onCreate()
And in your setViewValues() you accessing your class field variable.
So i am not sure that you are calling getSharedPreferences() on your field variable.
The same is about your spEditor. Fix this and try one more time.
If this will not help you, give as the rest of your code.
UPDATE
Try this mSettings = getSharedPreferences("prefs", Context.MODE_PRIVATE);
The mistake was using quotes around the key when storing my shared preference. The keys didnt match so nothing was persisted, sorry.
I need to set some values to their associated persistently stored data, if they exist, on initialization. If not I need to initialize them. Is there any disadvantage to using the SharedPreference to initialize the variable on the first run. That is, something like this :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sp = getSharedPreferences("MyDataName", Context.MODE_PRIVATE);
String name = sp.getString("name", "");
boolean isFirstRunning = sp.getBoolean("firstTime", true);
if (isFirstRunning) {
Toast.makeText(this, "YEA", Toast.LENGTH_LONG).show();
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("firstTime", false);
editor.commit();
}
}
If there is no disadvantage from a processing level, is there a standard practice as far as this situation is concerned? Also, is there any alternative way to handle the persistent data, or do we have to use SharedPreferences for this?
Yes that's perfectly acceptable. For neatness it may be better to define the keys, and default values as constants but the approach you have will work fine.
That is based on your requirement. if u need sharedpreference values quickly its good which you wrote. other wise no use.
I am making my first Android app, which consists of just editText's and Spinner's. Reading up on the activity cycle, I am wondering if it is even necessary to use the Bundle mechanism in my situation.
Since the state of the widgets are automatically persisted -
could I just call the getSelectedItem() method on the spinners and getText() on the EditText's within the onCreate() method for the Activity and pass that on to my newly re-created model object rather than using the Bundle mechanism? What are the advantages and disadvatanges of this approach?
The state of widgets it not automatically persisted. When you activity is destroyed it loses all the information about state. I recommend you saving you application state using shared preferences. Here is an example from google developers site. it allows you to save your application state by storing key-value pairs and it should suffice for your app.
Save the text and spinner item position in shared preferences when your activity is stopped - onStop() and restore the state in onCreate().
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();
}
}
Although you can save your application state by onSaveInstanceState(Bundle) method, usually the better way will be to do that in onPause() or onStop() methods(the data will be saved for sure). Documentation says:
Note that it is important to save persistent data in onPause() instead
of onSaveInstanceState(Bundle) because the latter is not part of the
lifecycle callbacks, so will not be called in every situation as
described in its documentation.
I'ma a bit confused here. I'm trying to change the value of an EditTextPreference, but it is not updated in the view. (This is in a PreferenceActivity)
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.modify_instrument_preferences);
// Set default values
SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = customSharedPreference.edit();
modifying = getObjectWithName(); //Some object with a name;
editor.putString("namePref", modifying.getName());
editor.commit();
android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}
My printlns print out valid information, and the commit() returns true, but on clicking the EditTextPreference, it displays the old value. If I rotate the screen, causing the onCreate to get run again, the EditTextPreference has the right value.
So perplexing. Why isn't this change being updated in the UI?
Edit:
I'm not sure why the above isn't working, but I managed to change it just by doing:
EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
namePref.setText("the text");
That updated the view everytime.
Although I know there are some constructs in place for PreferenceActivities to keep track of this info themselves, it doesn't seem to be well documented. I have found that adding an onPreferenceChangeListener to the preference will allow you to make those edits as soon as the preference is changed.
I am working in android. I am designing a file upload functionality.
This is my layout:
If I fill my entries like as title,price,category and then I press browse button for browse option then I go to BrowseActivity using startActivity(). But when I come back to this activity then all entries which were filled by me disappear. please suggest me what should I do for this so my entered entries save. If I do browse first then fill entries then it works properly.
What should I do for the case in which user first fill entries and then click on the browse button?
Use the SharedPreferences options to save all the Strings in onPause(). You can get them back in onResume() and fill out your text boxes. This is also nice since you can save the values that were entered and restore them each time the user leaves the app for any other reason.
EDIT:
Quick example:
Save your strings like so:
#Override
public void onPause(){
super.onPause();
// Save the user preferences during runtime for later use.
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("title", "Value of title");
editor.commit();
}
Then you get get the value back like this.
#Override
public void onResume(){
SharedPreferences settings = getSharedPreferences("aName", MODE_PRIVATE);
String title = settings.getString("title");
}
Here is what you need to do.
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putString("title", title.getText.toString());
//Do the same for the other 2 boxes.
super.onSaveInstanceState(savedInstanceState);
}
and in onRestoreInstanceState() pull the items out.
Like..
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
String Title = savedInstanceState.getString("title");
//Do the same for other String items you put into the bundle using the savedInstanceState() above. And then use EditText.setText(title); to set the text
}
The bundle is used exactly for this purpose. You Can get more info here
Check out android's shared preferences, they should give you an easy way to store data.
Android Shared Preferences
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/reference/android/content/SharedPreferences.html
Another way is to create an object which holds the data you need, and don't new it in the onResume method...