I have an ImageView ImageView1, whose background can be set by the user. How can I save the state of that background, so that when the user closes the app and reopens it, the background of ImageView1 is still the same?
Is it possible with onSaveInstanceState or do I have to write something different, and if so: How can I do this?
Right now I have:
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("ImageView1", imageView1);
but imageView1 gets red underline, even though declared before to id of ImageView
You can use shared preferences:
Save to shared preferences on change.
Get from shared preferences on app reopen.
Check documentation for more:
https://developer.android.com/training/data-storage/shared-preferences
You can use SharedPreferences as follows:
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("data", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("image", //put image path here);
editor.apply();
Then override the onResume method as follows
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("data", 0);
String imagePath = sharedPreferences.getString("image", ""); //default value is empty
}
Then load image using picasso or glide like..
Picasso.get().load(imagePath).into(imageview);
Related
I have a variable who contains data that can change when user is using app.
My goal is to store those data in SharedPrefs just before user is closing app,
I was thinking about something like
OnStop() {
Preferences.edit()... }
but i don't know the correct syntax ...
thanks in advance guys
Save your data in SavedPrefs in onStop Method.
Syntex will be like
In onStop Method
#Override
protected void onStop() {
super.onStop();
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = saved_values.edit();
edit.putString("key", "stringToBeSaved")
editor.commit();
}
And then to retrive your data in onCreate method
#Override
protected void onCreate(Bundle savedInstanceState) {
SharedPreferences saved_values = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String foo = saved_values.getString("key", "default_string");
}
Remember the key should be same.
For more info check out Android docs on
Shared Preferences: Save key-value data
Android Lifecycle: Understand the Activity Lifecycle
Activity.onStop() is called just before the app is completely closed (kicked from recents)
You should probably use Activity.onPause() to save your preferences as it will also be called when the user just switches to another app.
Further information:
https://developer.android.com/guide/components/activities/activity-lifecycle
You should save your persistent data in onPause() rather than in onStop().
Then you can retrieve your data in onResume().
For saving the data you can take a look at this example
SharedPreferences.Editor editor = getSharedPreferences("myPrefs", MODE_PRIVATE).edit();
editor.putString("username", "My name");
editor.apply();
And then retrience your data like this
SharedPreferences prefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
String username = prefs.getString("username", "No username"); //No username is the default value
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();
}
}
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();
}
}
How can I reload SharedPreferences when I resume from one activity to another? If I resume, it is possible that user has changed the settings. Is it possible to reload SharedPreferences or do I need to refresh/reload activity. And if, then how?
There is no difference in how you get and set SharedPreferences normally and from doing so in onResume. What you will need to do in addition to getting the most recent preferences, is update any objects you have in the Activity that use preference values. This will ensure your Activity is working with the most recent values.
A simple example:
protected void onResume() {
super.onResume();
getPrefs();
//...Now update your objects with preference values
}
private void getPrefs() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String myPref = prefs.getString("myPref", "");
}
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
}