Android App storing and calling Username and Passwords - java

I have an application that I want to create a log in activity. Ive got
1) Login (Button)
2) UserID (EditText)
3) Password (EditText)
I would like to store the username and password on the device's internal storage. How do I create the file from which the SharedPreferences pulls from and encrypt it?
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.clear();
if(etUserID.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putString("userID", txtUID.getText().toString().trim());
edit.putString("password", txtPass.getText().toString().trim());
edit.commit();
}
}
});
The txtUID and txtPass is showing up as red and when I delete it the system says that the getText is wrong.
This is my first shot at an authenticator. I found something called PasswordAuthentication from the android dev page but I haven't been able to find any tutorials or code of it being used.
SharedPreferences userDetails = getSharedPreferences("userdetails", MODE_PRIVATE);
String UID = userDetails.getString("userID", "");
String pass = userDetails.getString("password", "");
if (userDetails.contains("userID")||userDetails.contains("password")){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Sources Ive used for my research:
http://developer.android.com/reference/java/net/PasswordAuthentication.html
how to use getSharedPreferences in android
Update:
Ok, here is my updated code. If I don't enter a User ID or password it sets off my statements. However, the program doesn't go to the next activity when I put in the correct UserID and Password. I'm going to get it running first and then Ill move on to encrypting it.
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_on);
etUserID = (EditText) findViewById(R.id.etUserID);
etPassword = (EditText) findViewById(R.id.etPassword);
login_Button = (Button) findViewById(R.id.bLogin);
login_Button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals("")) || (etPassword.getText().toString().equals(""))) {
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
edit.putInt("userID", Integer.parseInt(etUserID.getText().toString()));
edit.putString("password", etPassword.getText().toString());
}
}
});
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
if (userDetails.equals(etUserID) && (userDetails.equals(etPassword))){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
Update:
I finally got it! Thanks for your help! Here is my complete code for this portion of the project. I still haven't encrypted it but I think I'm going to take a break and come back to it later. Thanks for all your help!
#Override
public void onClick(View v) {
int uid = 1155;
String pass = "pass";
SharedPreferences userDetails = getSharedPreferences(User_File, MODE_PRIVATE);
SharedPreferences.Editor edit = userDetails.edit();
edit.putInt("userID", uid);
edit.putString("password", pass);
edit.commit();
if((etUserID.getText().toString().equals(""))){
Toast.makeText(getApplicationContext(),"Please enter a User ID", Toast.LENGTH_LONG).show();
}else if (etPassword.getText().toString().equals("")){
Toast.makeText(getApplicationContext(),"Please enter a password", Toast.LENGTH_LONG).show();
}else{
String user_id = etUserID.getText().toString();
int user_id2 = Integer.parseInt(user_id);
String user_password = etPassword.getText().toString();
int userID = userDetails.getInt("userID", 1);
String password = userDetails.getString("password", "no name");
if (userID == user_id2 && password.equals(user_password)){
startActivity(new Intent(LogOn.this,CrimeMap.class));
}
}

Don't try to access the file. Let android do that, and encrypt the data you store to the shared preferences. I mean:
edit.putString("userID", encrypt(txtUID.getText().toString().trim()));
edit.putString("password", encrypt(txtPass.getText().toString().trim()));
You can use whatever encryption you like, though of course you'll need to decode it this way.
Another option is to store the SHA1 encrypted password, and in the authentication you compare the SHA1 encypted password that was typed in with the stored string. You could use http://mvnrepository.com/artifact/commons-codec/commons-codec for example:
String sha1Password = DigestUtils.sha1Hex(password);
edit.putString("sha1Password", encrypt(sha1Password);
To fix the "red" problem you'll need to declare txtUID, txtPass. They should be added to your layout somehow. Probably via editing the layout xml. But even programmatically you can do, like: Input text dialog Android

Related

Firebase Login should go to Home Screen if user already exists [duplicate]

This question already has answers here:
How to redirect multiple types of users to their respective Activities?
(3 answers)
Checking if a particular value exists in the Firebase database
(6 answers)
Closed 2 years ago.
First, I will tell the flow of my App.
Login Screen(SignInActivity.java) -> Enter details(MainActivity.java) ->Home Screen(HomeScreenActivity.java)
In my app, I have used Firebase Authentication and Firebase Database. When the user is new, then it should go to Main Activity from SignInActivity where user enters his name, a short description and his hobby. The details are stored in Firebase Database and then HomeScreenActivity opens where user details are shown in Recycler View.
But currently what happens is when same user does login again, it again asks user for details. I want to check if users Google Account already exists in Firebase Auth, then instead of asking details, it should directly go to HomeScreenActivity.
I checked many answers on StackOverflow, but nothing seems to work. One thing that i tried was additionalUserInfo.isNewUser but in this app crashes when user does login again, showing null error where I display user details in HomeScreenActivity.
SignInActivity.java
private void firebaseAuthWithGoogle(String idToken) {
AuthCredential credential = GoogleAuthProvider.getCredential(idToken, null);
mAuthIn.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "SignInWithCredential:success");
startActivity(new Intent(SignInActivity.this, MainActivity.class));
finish();
} else {
// If sign in fails, display a message to the user.
Toast.makeText(SignInActivity.this, "Authentication Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
MainActivity.java
public void init() {
hobbiesContinueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name=user.getText().toString().trim();
String desc=description.getText().toString().trim();
String hobby=spinner.getSelectedItem().toString();
String image="default";
String thumbnail="default";
if(!TextUtils.isEmpty(name))
{
FirebaseUser currentUser = FirebaseAuth.getInstance().getCurrentUser();
assert currentUser != null;
String userId=currentUser.getUid();
User user=new User(name,hobby,desc,image,thumbnail);
dbRef.child(userId).setValue(user);
startActivity(new Intent(getApplicationContext(), HomeScreenActivity.class));
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Enter a name",Toast.LENGTH_SHORT).show();
}
}
});
}
HomeScreenActivity.java
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
imgvw = headerView.findViewById(R.id.imageView);
imgvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//to open gallery
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
TextView nameDrawer = findViewById(R.id.navName);
TextView descDrawer = findViewById(R.id.navDescription);
User change = snapshot.getValue(User.class);
assert change != null;
//This is where null error occurs
nameDrawer.setText(change.getUserName());
descDrawer.setText(change.getUserDesc());
//change profile picture
image= Objects.requireNonNull(snapshot.child("userImage").getValue()).toString();
Log.d(TAG, "onComplete: "+image);
if(!image.equals("default")){
Picasso.get().load(image).placeholder(R.drawable.avatar).into(imgvw);
}
}
The solution is to save your user details in shared preferences for the first time when the user sign in , then after the user signs out and sign it again , you get data from shared preferences and set them directly to your edittexts
Try this Code :
///save sharedpreferences
SharedPreferences sharedPreferences =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username","put here your username"); //
editor.putString("email","put your email here"); //you can add more details
editor.apply();
///get sharedpreferences
SharedPreferences sharedPreferences1 =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
String username = sharedPreferences1.getString("username","");
String email = sharedPreferences1.getString("email","");
//then here set the valeus from sharedpreferences to your edittexts

How can you switch data from an activity that appears only once to another one that always appears, you register once and than you only need to login

HActivity.java
pass1 = (EditText) findViewById(R.id.edt1);
pass1c = (EditText) findViewById(R.id.edt2);
confirm = (TextView) findViewById(R.id.tv1);
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
if(pref.getBoolean("act_ex", false)){
String passs11 = pass1.getText().toString();
Intent intent = new Intent(this, LogInAct.class);
intent.putExtra("PASSWW", passs11);
startActivity(intent);
finish();
} else {
SharedPreferences.Editor ed = pref.edit();
ed.putBoolean("act_ex", true);
ed.commit();
}
// Its using java in Android Studio, it passes the password the first time you open the app but the second time you do that it will say wrong password (as I wanted) even if you type the right password (the one you registered with) how can I save it somewhere or do something with it?
LogInAct.java
tv2 = (TextView) findViewById(R.id.tv2);
edt3 = (EditText) findViewById(R.id.edt3);
Button loginbtn = (Button) findViewById(R.id.loginbtn);
loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
logpass = edt3.getText().toString();
passs1 = getIntent().getExtras().getString("PASSW");
passs11 = getIntent().getExtras().getString("PASSWW");
if (logpass.equals(passs1) && logpass.equals(passs11)) {
Intent intent = new Intent(getApplicationContext(), Photos.class);
startActivity(intent);
} else {
tv2.setText("wrong password");
}
}
});
So it looks to me like on your "registration" screen, you're capturing the username and password, and then passing them through the intent to the Login Screen? This works great in a single instance, but doesn't persist.
It's hard to tell just from the code, but how are you taking the user to the Login Screen on the next time they open the application? Is it just going to that screen as the launch?
Data passed over in intents is not persisted between sessions. It's most useful when passing data from one screen to another just for that session.
It can be used if you have a list screen and on the next screen is the detail screen. You want to pass the id of which item they clicked for example so you can load the data on that screen. But there is no reason to store it if they closed the app and opened it again.
To persist data between sessions, you want to store and extract from a more permanent storage. Ideally, you'll end up with a database system of some sort. But to answer what you're trying to do, use the shared preferences both for storing and extracting the password.
Registration:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putString("username", username);
editor.putString("password", password");
editor.apply();
Login:
SharedPreferences pref = getSharedPreferences("Apref", Context.MODE_PRIVATE);
passs1 = pref.getString("username");
Again, this is definitely not a good way to store user's credentials, but it answers your question of persistence.

Prevent user enter same username and email to the database

Currently I done using email authentication register new user to the database but now I met the problem of validate username and email which is prevent user enter the same username and password to the database so can you guys help me see whether the retrieve data statement got error?
auth = FirebaseAuth.getInstance();
db = FirebaseDatabase.getInstance();
ref = db.getReference();
FirebaseUser user = auth.getCurrentUser();
uid = user.getUid();//getuser id
run = (EditText) findViewById(R.id.Run);
rpw = (EditText) findViewById(R.id.Rpw);
rage = (EditText) findViewById(R.id.Rage);
//rbm = (RadioButton) findViewById(R.id.rbmale);
//rbfm = (RadioButton) findViewById(R.id.rbfemale);
re = (EditText) findViewById(R.id.Re);
rpn = (EditText) findViewById(R.id.Rpn);
ra = (EditText) findViewById(R.id.Ra);
rpc = (EditText) findViewById(R.id.Rpc);
//rbstd = (RadioButton) findViewById(R.id.rbstd);
//rbtt= (RadioButton) findViewById(R.id.rbtt);
final Button br = (Button) findViewById(R.id.Rbt);
br.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
usnm = run.getText().toString().trim();
pswd = rpw.getText().toString().trim();
email = re.getText().toString().trim();
ref.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Object a = dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if (TextUtils.isEmpty(usnm)){
Toast.makeText(Register.this, "Username cannot be empty", Toast.LENGTH_SHORT).show();
return;
}else if (usnm.length()<8){
Toast.makeText(Register.this, "Username cannot less then 8 characters", Toast.LENGTH_SHORT).show();
return;
}else if (usnm.length()>8){
Toast.makeText(Register.this, "Username cannot greater then 8 characters", Toast.LENGTH_SHORT).show();
return;
}else if (ref.child(uid).child("username").equals(usnm)){
Toast.makeText(Register.this, "Username had been taken already! Please try another one.", Toast.LENGTH_SHORT).show();
return;
}else if (TextUtils.isEmpty(pswd)){
Toast.makeText(Register.this, "Password cannot be empty", Toast.LENGTH_SHORT).show();
return;
}else if (pswd.length()<8){
Toast.makeText(Register.this, "Password cannot less then 8 characters", Toast.LENGTH_SHORT).show();
return;
}else if (pswd.length()>8){
Toast.makeText(Register.this, "Password cannot greater then 8 characters", Toast.LENGTH_SHORT).show();
return;
}else if (TextUtils.isEmpty(email)){
Toast.makeText(Register.this, "Email cannot be empty", Toast.LENGTH_SHORT).show();
return;
}else if (ref.child(uid).child("email").equals(email)){
Toast.makeText(Register.this, "Email had been taken already! Please try another one.", Toast.LENGTH_SHORT).show();
return;
}
register(usnm, pswd, email);
}//end of onclick
});
I hope can prevent user enter same input during registration.
To solve your problem, i recomand you implementing Firebase Authentication which is the best solution in your case. This approach solves all you problems regaring authentication and saves time because you don't need to maintain any code.
If you still want to use your approach, to check for uniqueness i recomand you change your database structure a little bit. In stead of using a unique key or the UID, i recomand you using the email address. It's also unique and very easy to use. Remember, using the UID is not always the best solution because if you let the user the possibility to delete his account, if he signs in again, another UID is generated and this will cause you troubles.
To check an email address / user-name also for uniqueness, i recomand you creating another nodes in your Firebase database (emailAddresses / userNames) in which you need to add all email addresses and all user-names. To verify the existents of a email address/user-name, just add a listener on that particular node and use the exists() method on the dataSnapshop object.
Hope it helps.
Here is the solution to take the uid after you have registered successfully a user on your Firebase. You need to add an onCompleteListener on your registration and after Firebase returns the uid you can query Firebase to get username and email.
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
//Problem with saving the data
if (databaseError != null) {
} else {
//User has registered, retrieve his uid
String uniqueKey = databaseReference.getKey();
}
}

Login Page shared preference not working as expected

I have an android app in which I am using shared preferences for login.Until now I have a flow like user logs in..when login is successful the credentials are stored.And when the user opens the app again the username password appears in the edit text.I have a login button and have setonclicklistner to login and jump to the inner activities.
I am trying a flow like when the user logs in successfully..and the app is restarted the credentials are stored..it should automatically go the next activity(inner activity).
What I have tried until now..
In oncreate the onclicklistner that opens next activity if credentials are good
buttonlogin.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(etemail.getText().toString().equals("") && etpass.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(),"Enter your username and Password",Toast.LENGTH_LONG).show();
}
else
{
load_data();
}
}
});
Code of shared pref
private void savePreferences() {
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
// Edit and commit
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.commit();
}
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
// Get value
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
}
What should I do in order to achieve this??if username password is stored automatically open next activity instead of clicking login button??
Thanks
you can use contains(String key) in SharedPreferences class
could be done in loadPreferences()
if login is only used to allow access to the next activity, then you don't need to simulate the button click, but if the click loads other data based on the provided username/password then you have to do it using performClick() in Button class.
so your code may look like this:
private void loadPreferences()
{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if(settings.contains(PREF_UNAME) && settings.contains(PREF_PASSWORD)){
//you can start the 2nd activity directly here
//Intent intent = new Intent (...)
//startActivity(intent);
//finish();
//OR
//load data into edittexts and programatically click the login button
UnameValue = settings.getString(PREF_UNAME, DefaultUnameValue);
PasswordValue = settings.getString(PREF_PASSWORD, DefaultPasswordValue);
etemail.setText(UnameValue);
etpass.setText(PasswordValue);
//here it will click the button as if the user did it.
btnLogin.performClick();
}//contains
}
Side note: it's not good practice (not secure) to store passwords in SharedPreferences specially plain-text, not encrypted
Open the next activity first, and then in onCreate method check if the user is logged in. If not close the first, and open the loggin activity.
MainActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
session = new SessionManager(getApplicationContext());
CheckLogin();
...
}
private void CheckLogin(){
if(session.checkLogin()){finish();}
}
SessionManager.java
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, LoginActivity.class);
// Closing all the Activities from stack
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);
return true;
}
return false;
}
After storing username and password in sharedpreference editor.putBoolean("hasLoggedin", true);
So it should be like
UnameValue = etemail.getText().toString();
PasswordValue = etpass.getText().toString();
editor.putString(PREF_UNAME, UnameValue);
editor.putString(PREF_PASSWORD, PasswordValue);
editor.putBoolean("hasLoggedin", true);
editor.commit();
then check in Oncreate method like
boolean hasLoggedin = sp.getBoolean("hasLoggedin", false);
if (hasLoggedin) {
Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
startActivity(intent);
finish();
}

One time Sign-in [duplicate]

This question already has answers here:
How to display a one time welcome screen?
(3 answers)
Closed 7 years ago.
I am creating a project where I have a login screen, which is used for user to login into the
Application. This login screen should only be visible the first time, so the user can fill it and log in, but when user opens the application at the second time the application must show main.activity. How to use Shared preferences to do this?
Save the login information of the user in SharedPeference:
SharedPreferences preferences = getSharedPreferences("preference",MODE_PRIVATE);
preferences.edit().putBoolean("LoggedIn", true).apply();
And save the boolean "LoggedIn" to false when the User logs out :
preferences.edit().putBoolean("LoggedIn", false).apply();
In the SplashActivity get the value from sharedprefence and call respective activities:
boolean loggedIn = preferences.getBoolean("LoggedIn", false);
if(loggedIn){
// call main activity
}else{
//call login activity
}
First, check whether user logged in before. Use SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
Boolean loggedIn = prefs.getBoolean("loggedIn", false);
if(loggedIn != null && loggedIn)
{
//open main activity
}else{
//open login page
}
and when user logs in, save the login information to SharedPreferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
prefs.edit().putBoolean("loggedIn", true);
That is all you need.
Try this, Working code
in your Login page
// Session Manager Class
SessionManagerFor_Signin session;
private EditText EMAIL, PASSWORD;
private Button login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.sign_in);
// Session Manager
session = new SessionManagerFor_Signin(getApplicationContext());
login = (Button) findViewById(R.id.loginbutton);
EMAIL = (EditText) findViewById(R.id.EmaileditText1);
PASSWORD = (EditText) findViewById(R.id.passwordeditText2);
login.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.loginbutton:
email = EMAIL.getText().toString();
password = PASSWORD.getText().toString();
if (email.equals("") || password.equals(""))
{
// user didn't entered user name or password
// Show alert asking him to enter the details
alert.showAlertDialog(sign_in.this, "Login Failed...","Please Enter Email and Password", false);
}
else
{
// fetch the Password form database for respective Email
storedPassword = DB.getSinlgeEntry(email);
if (password.equals(storedPassword))
{
session.createLoginSession(email, password);
Toast.makeText(sign_in.this, "Login Successfull",Toast.LENGTH_LONG).show();
Intent intent = new Intent(sign_in.this, Page1_Landing.class);
startActivity(intent);
finish();
}
}
break;
}
SessionManagerFor_Signin.java
public class SessionManagerFor_Signin
{
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Sharedpref file name
private static final String PREF_NAME = "SharedPref";
// All Shared Preferences Keys
private static final String IS_LOGIN = "IsLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_EMAILID = "email";
// Email address (make variable public to access from outside)
public static final String KEY_PASSWORD = "password";
// Constructor
public SessionManagerFor_Signin(Context context)
{
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
// Create login session
public void createLoginSession(String email, String password)
{
// Storing login value as TRUE
editor.putBoolean(IS_LOGIN, true);
// Storing name in pref
editor.putString(KEY_EMAILID, email);
// Storing email in pref
editor.putString(KEY_PASSWORD, password);
// commit changes
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())
{
Intent intent = new Intent(_context,Page1_Landing.class);
// Closing all the Activities
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//Toast.makeText(getApplicationContext(),email, Toast.LENGTH_LONG).show();
_context.startActivity(intent);
}
else
{
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, MainActivity.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 mail
user.put(KEY_EMAILID, pref.getString(KEY_EMAILID, null));
// user password
user.put(KEY_PASSWORD, pref.getString(KEY_PASSWORD, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser()
{
// Clearing all data from Shared Preferences
editor.clear();
editor.commit();
Intent intent = new Intent(_context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
_context.startActivity(intent);
}
/**
* Quick check for login
* **/
// Get Login State
public boolean isLoggedIn()
{
return pref.getBoolean(IS_LOGIN, false);
}
}
Further you want Reference Find below link
Link For Reference
SIf you want to do this with shared preferences when the user log in to the app share a preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", true).commit();
And if you want to log out on buton click set the preference..
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
prefs.edit().putBoolean("staylogin", false).commit();
In order to start your app without log in screen you can use a splash screen before the others and check the shared preference...
SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
Boolean state = prefs.getString("staylogin", false);
if (state) {
//Start Main Activity
} else {
//Start Log in activity
}

Categories

Resources