Introduction:-
Single time Login means Whenever we release Android Application in Android Market we
need allow login process to user only for single time. User enter his information and get login. When user open application second time then application directly jump on Main page instead of login page.
For this process we need to store some flag or value into database for further matching. For this,
we use SharedPreference.
Process:-
We create one static string variable in any activity which user must visit after login (Page which open after login page).
Write this code in onCreate () method of MainActivity.java
Write this code in onCreate () method of MainActivity.java
public static final String PREFS_NAME = "MyPrefsFile";
Then we need to create object of SharedPreference in MainActivity.java which can retrieve and modify value.Only one instance of the SharedPreference object is returned to any callers for
the same name.
SharedPreferences settings = getSharedPreferences(MainActivity.PREFS_NAME, 0);
getSharedPreferences():- Retrieve and hold the contents of the preferences file ''MainActivity.PREFS_NAME".
Parameter:-
1. name(MainActivity.PREFS_NAME):- Desired preferences file. If a preferences file by this name does not exist, it
will be created when you retrieve an editor (SharedPreferences.edit()) and then
commit changes (Editor.commit()).
Then we need to create instance of Editor.
SharedPreferences.Editor editor = settings.edit();
SharedPreferences
object. All changes you make in an editor are batched, and not copied back to
the original SharedPreferences
until you call commit()
or apply()
We set Boolean value to check user enter in this activity or not.
Following code for set value.
//Set "ifLoggedIn" to true
editor.putBoolean("hasLoggedIn", true);
// Commit the edits!
editor.commit();
Then we need to check this value in onCreate() method of LoginActivity.java whether user logged in or not.
SharedPreferences settings = getSharedPreferences(ExamGuideActivity.PREFS_NAME, 0);
//Get "hasLoggedIn" value. If the value doesn't exist yet false is returned
boolean hasLoggedIn = settings.getBoolean("hasLoggedIn", false);
if(hasLoggedIn)
{
startActivity(new Intent(this, FirstActivity.class ));
}
else
{
startActivity(new Intent(this, LoginActivity.class ));
}
Enjoy......
SAVE TREE SAVE LIFE
No comments:
Post a Comment