In my android application, I want to show the registration page only at the time of registration after that it will directly go to the main activity, doesn't go for registration page again if I open.
I did like this,It works but.
if I open my app and close it suddenly before registration process, the registration page didn't appear for the next time, without registration.
how can I avoid that.
How to write a condition to disappear the activity after the registration process.
SharedPreferences pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
if(pref.getBoolean("activity_executed", false)){
Intent intent = new Intent(this, Track.class);
startActivity(intent);
finish();
} else {
Editor ed = pref.edit();
ed.putBoolean("activity_executed", true);
ed.commit();
}
Guys please help!
SharedPreferences _RegPref;
boolean _UserType = "";
You have to check shref pref before setcontentview method Like:
_RegPref = getApplicationContext().getSharedPreferences("LoginPref", 0);
_UserType = _RegPref.getString("REGISTERD", _UserType);
if (_UserType==true) {
try {
startActivity(new Intent(_ctx, YourActivity.class));
finish();
overridePendingTransition(R.anim.enter_new_screen, R.anim.exit_old_screen);
} catch (Exception e) {
e.printStackTrace();
}
}else {
set contentview("your register activity view");
}
after the registration is succesful, save the values in shred pref like:
Editor prefsEditor = _RegPref.edit();
_UserType = false;
prefsEditor.putString("REGISTERD", _UserType);
prefsEditor.commit();
you are in currect way, save sharedpreferences for this.
When user successfull register in your app, at that time save sharepreferences.
In onCreate method, if no sharepreferences found then forward to registration page.
Hi you can save sharedpreferences using bellow code.
This is the standard method for write shared preferences.
/**
* write SharedPreferences
* #param context
* #param name, name of preferences
* #param value, value of preferences
*/
public static void writePreferences(Context context,String name,String value)
{
SharedPreferences setting= context.getSharedPreferences("Give_your_filename", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=setting.edit();
editor.putString(name, value);
editor.commit();
}
Save your preferences.
Follow this link click here
Related
I have integrated Google sign in sample application with my applications Main Activity.
I have a button in my Navigation header to launch login activity.
When I login with my google account, it fetches my name and email Id into Navigation Header.
Now the issue is, if I quit this app, I need to sign in again every time. How can I save the login details.
I have gone through multiple articles which talk about Shared Preference, however shared preference doesn't work for me.
Below is one of the code snippet I have tried. I am calling storeUserDetails() in onBackPressed and getUserDetails() in onCreate().
public void storeUserDetails(String userName, String emailID){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
SharedPreferences.Editor mEditor = mSharedPreference.edit();
mEditor.putString("userFullName",userName);
mEditor.putString("userEmailID",emailID);
mEditor.apply();
}
private String getUserDetails(){
mSharedPreference = getSharedPreferences("userDetails",MODE_PRIVATE);
return mSharedPreference.getString("userFullName","#gmail.com");
}
Tried this tutorial as well
https://www.tutorialspoint.com/android/android_shared_preferences.htm
//First instantiate sharedpreferences
SharedPreferences sharedpreferences;
sharedpreferences=getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
private String name,phone,email;
//OnPause method to save shared preferences when activity is destroyed
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Name, name);
editor.putString(Phone, phone);
editor.putString(Email, email);
editor.commit();
}
//OnResume method used to retrieve sharedpreferences
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
SharedPreferences prefs = this.getSharedPreferences("MyPREFERENCES", Context.MODE_PRIVATE);
name = prefs.getString("Name","");
phone = prefs.getString("Phone","");
email = prefs.getString("Email","");
}
Also to handle the login issue, you could use your launcher activity and sharedpreferences to check if Name is null, if it isn't then navigate to your mainactivity, and if it is then navigate to login, then on your logout function just make sure you clear the sharedpreferences.
I am allowing registered users to access the app. The users have to login every time they open the app. So I want to know how to login the app single time like facebook or whatsapp?
You can use Shared Preferences .
Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key,value pair.
SO Help .
You can save and retrieve key, value pair data from Shared
preferences. SharedPreferences values will persist across user
sessions.
Data in shared preferences will be persistent even though user closes
the application.
You can get values from Shared preferences using
getSharedPreferences() method.
You also need an editor to edit and save the changes in shared
preferences.
Use SharedPreferences to store data: booleans, floats, ints, longs,
and strings.
Demo
Android User Session Management using Shared Preferences
Android Working with Shared Preferences
public class SessionManager {
// Email address (make variable public to access from outside)
public static final String KEY_api = "apikey";
private static final String KEY_NAME = "name";
// Sharedpref file name
private static final String PREF_NAME = "AndroidHivePref";
private static final String push_ = "AndroidHivePref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
SharedPreferences.Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Constructor
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void createLoginSession(String name, String apikey) {
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_NAME, name);
// Storing email in pref
editor.putString(KEY_api, apikey);
// commit changes
editor.commit();
}
public int getMerchentPushCount() {
return pref.getInt("MerchentPushCount", 0);
}
public void setMerchentPushCount(Integer count) {
editor.putInt("MerchentPushCount", count);
editor.commit();
}
/**
* Check login method wil check user login status
* If false it will redirect user to login page
* Else won't do anything
*/
public void checkLogin() {
// Check login status
if (!this.isLoggedIn()) {
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Staring Login Activity
_context.startActivity(i);
}
}
/**
* Get stored session data
*/
public HashMap<String, String> getUserDetails() {
HashMap<String, String> user = new HashMap<String, String>();
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user api key
user.put(KEY_api, pref.getString(KEY_api, null));
// return user
return user;
}
/**
* Clear session details
*/
public void logoutUser() {
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to Loing Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
// Staring Login Activity
_context.startActivity(i);
}
/**
* Quick check for login
* *
*/
// Get Login State
public boolean isLoggedIn() {
return pref.getBoolean(IS_LOGIN, false);
}
}
create a class for sheared prefrence, and call it in ur activity which u wants to make as a landing page. for reference follow this tutorial
You should use SharedPreferences to store the successful login action.
Saving the state in Shared Preferences
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("username", "yourUserName");
editor.putBoolean("isLoggedIn", true );
editor.commit();
Retrieving the state from SharedPreference
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
boolean isLoggedIn = prefs.getBoolean("isLoggedIn", false);
if (isLoggedIn) {
// Don't display login activity
} else {
// Display Login Activity
}
static int existingCounter;
Context mContext = SplashScreen.getContextOfApplication();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
public static int cCounter()
{
MainMenu mm = new MainMenu();
existingCounter = mm.getExistingCounter();;
return existingCounter;
}
public void setSharedPreferences(int count)
{
SharedPreferences preferences = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("existingCount", existingCounter);
editor.commit();
}
//Get value from shared preferences
public int getExistingCounter()
{
SharedPreferences myPrefs = mContext.getApplicationContext().getSharedPreferences("myCounter", 0);
myPrefs.getInt("existingCount", 0);
return existingCounter ;
}
Hi all, above is my shared preferences. What I am trying to achieve is when user 1st launch the app, my app shall direct user to the disclaimer page and after the user agree to the T&C then in future the user launch the app shall not show the disclaimer page again. However, my current codes only valid when user never exit app. If the user were to exit the app and relaunch, my app still shows the disclaimer page. Please assist =) Thank you in advance. Below is the part where I set the sharedpreferences:
case 3:
cCounter();
if(existingCounter==0)
{
changeMenuFrag(new AcknowledgePg());
existingCounter++;
setSharedPreferences(existingCounter);
}
else
{
changeMenuFrag(new GalleryMain());
}
break;
Save a flag in the Preferences when you start up the application, after you've done the welcome screen stuff. Check for this flag before you show the T&C screen. If the flag is present (in other words, if it's not the first time), don't show it. Instead of a integer counter use a boolean flag and in your main activity check if the flag is true or false based on that show the appropriate activity.
SharedPreferences mPrefs;
final String welcomeScreenShownPref = "welcomeScreenShown";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
// second argument is the default to use if the preference can't be found
Boolean welcomeScreenShown = mPrefs.getBoolean(welcomeScreenShownPref, false);
if (!welcomeScreenShown) {
// here you can launch another activity if you like
SharedPreferences.Editor editor = mPrefs.edit();
editor.putBoolean(welcomeScreenShownPref, true);
editor.commit(); // Very important to save the preference}
}
I am getting trouble in making only one time login... My aim is first user gets login screen.. If he is new user he will register and then login...from then when ever user starts the application he should directly redirect to main activity that is to skip the login page..please friends help me out from this problem..please post me any tutorials or any code...please tell me how to modify in manifest file also...
I am using like this in login activity but i didn't achieve my task.
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
editor.putString("register","true");
editor.commit();
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true"))
// redirect to next activity
else
// show registration page again
Implement your SharedPreferences this way:
Boolean isFirstTime;
SharedPreferences app_preferences = PreferenceManager
.getDefaultSharedPreferences(Splash.this);
SharedPreferences.Editor editor = app_preferences.edit();
isFirstTime = app_preferences.getBoolean("isFirstTime", true);
if (isFirstTime) {
//implement your first time logic
editor.putBoolean("isFirstTime", false);
editor.commit();
}else{
//app open directly
}
check it here
http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/
A very good example of session management in android app.
Use SharedPreferences. contains which tell an key is present or not in SharedPreferences. Change your code as:
SharedPreferences pref;
SharedPreferences.Editor editor;
pref = getSharedPreferences("testapp", MODE_PRIVATE);
editor = pref.edit();
if(pref.contains("register"))
{
String getStatus=pref.getString("register", "nil");
if(getStatus.equals("true")){
redirect to next activity
}else{
//first time
editor.putString("register","true");
editor.commit();
/// show registration page again
}
}
else{ //first time
editor = pref.edit();
editor.putString("register","true");
editor.commit();
/// show registration page again
}
You can visit my blog
http://upadhyayjiteshandroid.blogspot.in/2013/01/android-working-with-shared-preferences.html
hope you will get the answer and understanding clearly
Boolean flag;
SharedPreferences applicationpreferences = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = applicationpreferences .edit();
flag = applicationpreferences .getBoolean("flag", false);
if (flag) {
///second time activity
}else{
//first time
editor.putBoolean("flag", true);
editor.commit();
}
Check out the Session Management in Android which shows you the way how you can manage the login if user is already logged into the application or not. And switch the user accordingly.
Hope this will help you.
1.for storing in stored preferences use this
SharedPreferences.Editor editor = getSharedPreferences("DeviceToken",MODE_PRIVATE).edit();
editor.putString("DeviceTokenkey","ABABABABABABABB12345");
editor.apply();
2.for retrieving the same use
SharedPreferences prefs = getSharedPreferences("DeviceToken",
MODE_PRIVATE);
String deviceToken = prefs.getString("DeviceTokenkey", null);
I am developing an android application which should authenticate user only once in his mobile after installing the app. It should not ask the details for the second time. For this I have used shared preferences by setting a Boolean value. But it,s not working. Is there any suggestions here.. thanks friends !! My code is here
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", true);
editor.commit();
use it this way :
in your onCreate() use :
if (isFirstTime()) {
// do what you want to do only once
}
to call the below :
private boolean isFirstTime()
{
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
boolean ranBefore = preferences.getBoolean("RanBefore", false);
if (!ranBefore) {
// first time
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("RanBefore", true);
editor.commit();
}
return !ranBefore;
}
Your approach of using SharedPreference is correct.Put the below coad snippet in your oncreate() method of the Activity.
SharedPreferences prefs=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
register = prefs.getBoolean("Register",false);
if(!register)
{
//register user
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("Register", register);
editor.commit();
}
else{
//continue with the rest
}
the first time :
settings.edit().putBoolean("Register", true).commit();
and in onCreate you do the test
if(!settings.getBoolean("Register",false))
//it isn't the first time
So the full code :
SharedPreferences settings = getSharedPreferences("settings", 0);
if(!settings.getBoolean("Register",false)){
//it isn't the first time
}
else{
settings.edit().putBoolean("Register", true).commit();
}