How to make in app changes persist so that when app relaunches all settings remain same(like if from app i have selected vibration then when app is not running if my phone is ringer mode when app relaunches it sets itself to vibration)?
There's actually multiple ways to persist changes. The Android documentation covers all of them in more detail, but essentially these are the five ways. Easiest is SharedPreferences, probably.
Shared Preferences
Store private primitive data in key-value pairs.
Internal Storage
Store private data on the device memory.
External Storage
Store public data on the shared external storage.
SQLite Databases
Store structured data in a private database.
Network Connection
Store data on the web with your own network server.
Use SharedPreferences. You can put key value pairs and retrieve when needed .
You need to store these settings within the Database. On how to use this see Using Databases
Use SharedPreferences
Save your settings:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("email", "my_email#email.com");
editor.putString("name", "Albert");
editor.commit();
Retrieve them:
SharedPreferences prefs = getSharedPreferences("myprefs",Context.MODE_PRIVATE);
String email = prefs.getString("email", "default#email.com");
Thing that you could do is to create a PreferenceActivity like :
public class Prefs extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
}
In res/xml folder add preference.xml with this content :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<PreferenceCategory android:title="General" >
<CheckBoxPreference
android:key="notification"
android:summaryOff="You will not receive any notification"
android:summaryOn="Notifications are sent to your device"
android:title="Get notification" />
</PreferenceCategory>
</PreferenceScreen>
In your code you can do now :
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Boolean sendNotification = prefs.getBoolean("notification", false);
Related
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 have one log in page for the project 'x'.My need is if at first i entered into the project by providing proper values in to the log in page of the project.The project always want to be signed-in, whenever i try to open the project.How to achieve this concept?
Thanks for your precious time!..
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 the 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 = PreferenceManager.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.
For more info, check this link:
Making data persistent in android
Whenever you login set the user inside the preference file. Then in your main activity give a check whether you have value for this preference or not. If present, goto the landing page. Otherwise show the login page.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
getLandingPage();
}
private void getLandingPage() {
if (isLoggedIn()) {
//goto login page
} else {
//goto landing page
}
}
/**
* Checks whether preference contains any value
*
* #return
*/
private boolean isLoggedIn() {
return ProjectPreferences.getUserName() == ProjectPreferences.NULL_STRING
? true
: false;
}
}
Also don't forget to set username while you login.
I am developing an Android app where the user has the facility of Facebook sharing. I have the login details of the user for the Facebook, now what I am trying to do is these login details should be saved until the application is not deleted.
When I tried to find the answer for this, I got some answers stating about shared preferences. But I am not cleared exactly how it works.
Here is what I am trying to do,
Username = username.getText().toString();
PassWord = password.getText().toString();
where username and password are 2 edittext fields. When the user enters for the first time into Facebook, I should save these data somewhere for my future reference so that he need not login again.
Can any one let me know how to achieve this?
// Save your info
SharedPreferences settings = getSharedPreferences("my_file_name", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("username", username.getText().toString());
editor.putString("password", password.getText().toString());
editor.commit();
// Obtain your info
SharedPreferences settings = getSharedPreferences("my_file_name", 0);
String username = settings.getString("username", "");
String password = settings.getString("password", "");
A file will be created in:
data/data/[your.package.path]/shared_prefs/[your.package.path]_preferences.xml
You can use sharedPreference for this.
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.
Don't Use preferences to save facebook data:
Please use this code in Oncreate method:
if (isLoggedIn()) {
layout_after_fb_login.setVisibility(View.VISIBLE);
updateUI();
} else {
layout_after_fb_login.setVisibility(View.GONE);
}
////
private boolean isLoggedIn() {
AccessToken accesstoken = AccessToken.getCurrentAccessToken();
return !(accesstoken == null || accesstoken.getPermissions().isEmpty());
}
private void updateUI() {
Profile profile = Profile.getCurrentProfile();
if (null != profile) {
profilePictureView.setProfileId(profile.getId());
userNameView.setText(String.format("%s %s", profile.getFirstName(), profile.getLastName()));
layout_after_fb_login.setVisibility(View.VISIBLE);
} else {
layout_after_fb_login.setVisibility(View.GONE);
}
}
I have a small ap with preferences. In this class I've set the onPreferenceClick to get coordinates from the GPS. When the listener returns, my hope was to set the lat / long textedits automatically. I've tried every source sample out there, no luck:
public void onLocationChanged(Location l) {
Log.d("H","Location Received: "+l.toString());
prefLocation.setSummary(l.toString());
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor1 = settings.edit();
editor1.putString("posLat","xxx");
editor1.commit();
}
When this code executes when I click on my PreferenceScreen and the location listener returns, the EditTextPreference with the key "posLat" still shows the old value.
I'm going crazy trying to figure out what's wrong!
My prefs.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="My_Shared_Preferences">
<PreferenceCategory
android:title="Your Location">
<PreferenceScreen
android:title="Find Location..."
android:key="location"
android:summary="Click here to read your location automatically"/>
<EditTextPreference
android:title="Latitude"
android:key="posLat" />
<EditTextPreference
android:title="Longtitude"
android:key="posLong" />
<EditTextPreference
android:title="Altitude"
android:key="posAlt" />
</PreferenceCategory>
</PreferenceScreen>
Alternatively, maybe there is a better way to store the location value for an application? I don't really want the user to manually enter the coordinates, but I dont want to resort to saving and loading a text file with the settings, it seems so crude.
I've been having kind of the same problem. My solution was to use the default shared preferences instead of manually created preferences with a given name.
Change the reference to SharedPreferences from this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
to this:
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
and see if that makes any difference.
Seems that this has actually changed (see 1 and 2)
The new way to do this is
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(PREF_NAME, YOUR_VALUE);
editor.commit();
What is "the old value". With the code that you've posted it looks like the only thing that is going to get stored in your preferences is the String "xxx" you need to replace that with a string that represents the location inside your putString() method.
This question already has answers here:
How do I get the SharedPreferences from a PreferenceActivity in Android?
(6 answers)
Closed 7 years ago.
I need simple explanation about shared preference in android and preference data
According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,
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.
SharedPreferences Example:
package com.example.test;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
public class SharedPreferencesDemo extends Activity {
SharedPreferences shared_preferences;
SharedPreferences.Editor shared_preferences_editor;
String test_string = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
shared_preferences = getSharedPreferences("shared_preferences_test",
MODE_PRIVATE);
test_string = shared_preferences.getString("test_key", "Default");
Toast.makeText(getApplicationContext(), test_string, Toast.LENGTH_SHORT)
.show();
shared_preferences_editor = shared_preferences.edit();
shared_preferences_editor.putString("test_key", "Hello World");
shared_preferences_editor.commit();
test_string=shared_preferences.getString("test_key", "Default");
Toast.makeText(getApplicationContext(), test_string, Toast.LENGTH_SHORT).show();
}
}
Here is the post: http://www.codestacks.in/2013/03/sharedpreferences/