I have 3 activities in my Gingerbread 2.3.3 application for Android which I'm constructing in Eclipse.
1) MainActivity --- two options, go to LoginActivity or go directly to HomeScreenActivity
2) LoginActivity --- Enter login credentials (aka username and password), validate, and then store in SharedPreferences. After successfully validating, it goes to the HomescreenActivity. Here's what I have for the SharedPreferences section in LoginActivity:
public static final String PREFS_FILE = "MY_PREFS";
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("USERNAME", getUsername());
editor.putString("PASSWORD", getPassword());
editor.commit();
3) HomescreenActivity --- a basic homescreen that shows who's logged in right now in the top right corner in a TextView. For this my onResume() contains:
public static final String PREFS_FILE = "MY_PREFS";
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_PRIVATE);
TextView name_text = (TextView) findViewById(R.id.name_text_vw);
name_text.setText(prefs.getString("USERNAME", "");
When I use the LoginActivity and login, I properly see the username in the TextView on the HomescreenActivity. However, when I exit the application and do some other stuff to get the activity off the stack, I want to go back to the application, go directly to my HomescreenActivity and see my username logged in already. But this doesn't happen. Does anyone know why? I thought SharedPreferences was the way to store settings and data even after you've left your application. Maybe I'm not using the correct mode -- aka MODE_WORLD_READABLE or MODE_WORLD_WRITABLE?
There are shared prefs for activities, and shared prefs for apps. Maybe you are using activity prefs.
To save to preferences:
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("MYLABEL",
"myStringToSave").commit();
To get a stored preference:
PreferenceManager.getDefaultSharedPreferences(context).getString("MYLABEL",
"defaultStringIfNothingFound");
Where context is your Context.
I have to say I don't know the answer to your specific question, I suspect it's because getSharedPreferences is not static and is a method of a Context. Therefore, you have no control over when commit() actually writes to store. However, I recommend a different approach.
I use a static reference in a custom class which extends Application.
public class MyApp extends Application
{
protected static SharedPreferences preferences;
public static void loadPreferences(Context context) {
// load your preferences
}
public static void savePreferences(Context context) {
// save your preferences
}
You can access them via MyApp.preferences.
Don't forget to add your Application class to the manifest.
Good luck!
Related
*I'm new in learning android
I'm searching for any website that show on how to accept user detail for example name and age, and display it in another activity using sharedpreferences in newer version of code? Do you have any? The another activity will have a Back button pointing to the first activity. All I found was in older version and not matched in my Android Studio so, I've cancelled the program. Anyone?
In the first activity, you can save the user name and age like this:
private void saveUserInformation(String userName, int age) {
//In this activity save the name in the shared preference
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("user_name", userName).putInt("user_age", age).apply();
}
In the second activity, to get the user information, do this:
private void getUserInformation() {
//In the second activity or any other activity, you can get the userName and age like thi
SharedPreferences sharedPreferences = getSharedPreferences("myAppPrefs", Context.MODE_PRIVATE);
String userName = sharedPreferences.getString("user_name", null);
int userAge = sharedPreferences.getInt("user_age", 0);
}
From your question and comment in other answers, i guess you need more explanation on how a shared preference works. When you save data in a sharedpreference, it gets saved in a file on the user device. After saving you can access that data from any activity as long as the activity has access. All you just have to do is put it in a shared preference using a unique key and get it where you need it using that same unique key. Hope it helps. If i my answer helps, don't forget to upvote. Thanks.
this is how you create a sharedpref
SharedPreferences sp=getSharedPreferences("MYPREFNAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sp.edit;
this is how you put data in it
editor.putString(key,string);
this.is how you retrieve that string back
sp.getString(key,DefaultString);
//in your first activity use
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("name","name_value").apply();
sharedPreferences.edit().putInt("age",age_value).apply();
//and now in your second activity to retrieve data
SharedPreferences sharedPreferences=getSharedPreferences("your_packagename", Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
int age =sharedPreferences.getInt("age",0);
In one of my views the user makes a selection. I want to store that selection in a variable I can use across all views so it can be used for further database queries such as "bookId".
How can I make "bookId" a global variable that is set on one view and can be accessed across the other views when needed?
----- Edit: What I'm attempting to do based on comments and answers -----
On my main activity where the SharedPreference is stored I have this before the onCreate:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Integer bookId;
In my onCreate I've done this:
settings = getSharedPreferences(PREFS_NAME, 0);
bookId = settings.getInt("bookId", 0);
After the button press I'm storing a custom attribute and attempting to set bookId in the SharedPreference:
SharedPreferences.Editor editor = settings.edit();
editor.putInt("bookId",bookKey);
editor.commit();
In another view I'm attempting to get the bookId from the SharedPreference and, for testing purposes, I'm trying to set the stored value to a textView just to make sure it stored and carried over correctly.
Before the onCreate on the second view:
public static final String PREFS_NAME = "myPrefs";
SharedPreferences settings;
Inside the onCreate:
settings = getSharedPreferences(PREFS_NAME, 0);
Integer bookId = settings.getInt("bookId", (Integer) null);
tempBookTextView = (TextView) findViewById(R.id.tempBookTextView);
tempBookTextView.setText(bookId);
I have a two questions, how does this look so far? Any ideas why the app crashes when I use
Integer bookId = settings.getInt("bookId", (Integer) null);
Instead of using global variable to access variable value through out the app try using SharedPreferences.
sample activity:
public class Book extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
String mBookId = null;
#Override
protected void onCreate(Bundle state){
super.onCreate(state);
. . .
// Restore preferences
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
mBookId = settings.getString("book_id", null);
// use book_id;
}
#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.putString("book_id", mBookId);
// Commit the edits!
editor.commit();
}
}
Preferences are typically created private and can be accessed via all over the application components. Sharing data with other application with world readable or writable preference file is rarely used, as the external component would need to know the exact filename and location of the file.
To kill the spirit of encapsulation,
public class Globals {
public static int x;
public static int y;
}
and later
if (Globals.x == 0) { ... }
But please don't do exactly that, any class can contain static variables, find a class responsible for the value you want to store.
OTOH, android processes may be restarted when you don't expect it, in which case all the variables will be reset. So it's better to use shared preferences and if they don't work as expected (which I have seen in at least one release of Android), store the instance of shared preferences in a static variable.
You can use Shared Preferences
Saved at once !
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(ProjectAct.this).edit();
editor.putInteger(StaticVariable.BOOKID, "1");
p.get("contract_no"));
editor.commit();
Then call from anywhere like that
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
int book_id = prefs.getInteger(StaticVariable.BOOKID,null);
See more at How to use SharedPreferences in Android to store, fetch and edit values
I want to know if there is a way to pass all the extras to the new intent.
Is it possible? And is it a good idea?
The reason is that I want to save the login state as a json string, and pass it in between Activities. I don't want to store data with SQLite or anything. Can I bypass all the intent extras to the new intent ?
please consider Shared Preference :
// Declaration
public static String KEY = "SESSION";
public static void saveUserName(String username, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("username", username);
editor.commit();
}
public static String getUserName(Context context) {
SharedPreferences savedSession = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedSession.getString("username", "");
}
You can store the login credentials to preference and retrieve them as well in any of your activity.
SaveUsername("Your text to save", Your_activity.this);
And to retrieve the value
String mUserName = getUserName(YourActivity.this);
It is recommended to have all your preference methods in your utils class to keep the code organized.
You can read more here
yes you can use Shared Preference to save the Login session of user here is handy example of managing session using shared preference http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ I used it earlier and suggest you to have a look at it.
Any of the two may help you.
Saving it in the sharedPreference file.
If you want them to be accessable throught the application you can use the applicationClass, like a global singleton.
I'm a novice Android developer who are currently trying hard to build a Login Screen.
I need to find the easiest way to store the username and password in 1 class and retrieve it from another class. See Google has provided several ways: http://developer.android.com/guide/topics/data/data-storage.html
which one is the most efficient and easy to code?
thanks!
For Login screen tasks like storing username and password you can use Shared Preferences. Here I had made custom methods for using shared preferences. Call savePreferences() method and put your Key and Value(as savePreferences() is based on XML), similarly call Load with your Key. And lastly don't forgot to call deletePreferences() on LOGOUT.
/**
* Method used to get Shared Preferences */
public SharedPreferences getPreferences()
{
return getSharedPreferences(<PREFRENCE_FILE_NAME>, MODE_PRIVATE);
}
/**
* Method used to save Preferences */
public void savePreferences(String key, String value)
{
SharedPreferences sharedPreferences = getPreferences();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
/**
* Method used to load Preferences */
public String loadPreferences(String key)
{
try {
SharedPreferences sharedPreferences = getPreferences();
String strSavedMemo = sharedPreferences.getString(key, "");
return strSavedMemo;
} catch (NullPointerException nullPointerException)
{
Log.e("Error caused at TelaSketchUtin loadPreferences method",
">======>" + nullPointerException);
return null;
}
}
/**
* Method used to delete Preferences */
public boolean deletePreferences(String key)
{
SharedPreferences.Editor editor=getPreferences().edit();
editor.remove(key).commit();
return false;
}
Define some statics to store the preference file name and the keys you're going to use:
public static final String PREFS_NAME = "MyPrefsFile";
private static final String PREF_USERNAME = "username";
private static final String PREF_PASSWORD = "password";
You'd then save the username and password as follows:
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, username)
.putString(PREF_PASSWORD, password)
.commit();
So you would retrieve them like this:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String username = pref.getString(PREF_USERNAME, null);
String password = pref.getString(PREF_PASSWORD, null);
if (username == null || password == null) {
//Prompt for username and password
}
Alternatively, if you don't want to name a preferences file you can just use the default:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
For your purpose both, SQLite Database and SharedPreferences will work. But I would suggest SharedPreferences as they are very easy to use. Some ppl like to create a class to hold variables like this but the benefit of SQLite and SharedPreferences file is that the user login name and password information will be with you even if the app goes in background and gets destroyed. So when the user comes back to your app, you can sign them in again without asking for password. If user explicitly decides to logout, you can simply remove the login information from shared preferences file
The easiest way of retrieving log in information from other activities is using "SharedPreferences". I strongly recommend this method for storage and retrieval of Username and Password. Because you can access this information from anywhere in the application without any complications. The log in information may have to use repeatedly in an application.
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
i am creating login in my app. User type his info i send it to web service to check and get his ID. Now i need to save it somewhere in my app that i could check if he had login.
So where this info should be saved ? I know that every app have it's settings so there should be this info ? Maybe someone could give me more info what and how this is doing.
Thanks.
I found this post:
What is the most appropriate way to store user settings in Android application
I believe my question was duplicate. But it would be nice if you have something to share more.
First of all save user info like uname & password in SharedPreferences with this code.
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("Username",txtUname.getText().toString());
editor.putString("Password",txtPWD.getText().toString());
editor.commit();
and then get SharedPreferences from below code
SharedPreferences settings = getSharedPreferences("UserInfo", 0);
txtUname.setText(settings.getString("Username", "").toString());
txtPWD.setText(settings.getString("Password", "").toString());
Answer is Use Application Class or Shared Preferences
I assume you can easily search for the Example of Application Class, SharedPreferences and SQLite Database
So I am mentioning Where Do I Use Which Options
Application Class
When I got anything(var , array , list , objects) to store just only for the LifeTime of the Application..and As it got close (for Android Force Close) I use Application Class.
SharedPreferences
I use this when I got some short information like id,token,username,flags and I want to store that as long as the application rest in the Device..and need to use those information everytime I start the Application..
SQLite Database
When there is a bulk data in Record format (Row - Column) I used it to store in database so it becomes easy to store , retrive and manipulate.
You can use SharedPreferences for this.
Some codes from references (taken from documentation):
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();
}
}
if user clear the application data from setting -> application manager -> your application -> clear data
then all data saved in shared preferences will get removed