I\'m new to Android. I\'m doing an app for an university exam. I have to do an application for a travel agency. I\'d like to manage the user session with shared preferences
This is working code, try it.
MainActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
Reg.java
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Reg extends ActionBarActivity {
SharedPreferences sharedPreferences;
Editor editor;
Button buttonReg2;
EditText txtUsername, txtPassword, txtEmail;
UserSession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reg);
txtUsername = (EditText) findViewById(R.id.Name);
txtPassword = (EditText) findViewById(R.id.txtPassword);
txtEmail = (EditText) findViewById(R.id.Email);
buttonReg2 = (Button) findViewById(R.id.buttonReg2);
// creating an shared Preference file for the information to be stored
// first argument is the name of file and second is the mode, 0 is private mode
sharedPreferences = getApplicationContext().getSharedPreferences("Reg", 0);
// get editor to edit in file
editor = sharedPreferences.edit();
buttonReg2.setOnClickListener(new View.OnClickListener() {
public void onClick (View v) {
String name = txtUsername.getText().toString();
String email = txtEmail.getText().toString();
String pass = txtPassword.getText().toString();
if(txtUsername.getText().length()<=0){
Toast.makeText(Reg.this, "Enter name", Toast.LENGTH_SHORT).show();
}
else if( txtEmail.getText().length()<=0){
Toast.makeText(Reg.this, "Enter email", Toast.LENGTH_SHORT).show();
}
else if( txtPassword.getText().length()<=0){
Toast.makeText(Reg.this, "Enter password", Toast.LENGTH_SHORT).show();
}
else{
// as now we have information in string. Lets stored them with the help of editor
editor.putString("Name", name);
editor.putString("Email",email);
editor.putString("txtPassword",pass);
editor.commit();} // commit the values
// after saving the value open next activity
Intent ob = new Intent(Reg.this, Login.class);
startActivity(ob);
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
Login.java
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends ActionBarActivity {
//public static android.content.SharedPreferences SharedPreferences = null;
private static final String PREFER_NAME = "Reg";
Button buttonLogin;
EditText txtUsername, txtPassword;
// User Session Manager Class
UserSession session;
private SharedPreferences sharedPreferences;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
Button switchButton = (Button)findViewById(R.id.buttonReg);
switchButton.setOnClickListener (new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(Login.this, Reg.class);
startActivity(intent);
}
});
// User Session Manager
session = new UserSession(getApplicationContext());
// get Email, Password input text
txtUsername = (EditText) findViewById(R.id.txtUsername);
txtPassword = (EditText) findViewById(R.id.txtPassword);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
// User Login button
buttonLogin = (Button) findViewById(R.id.buttonLogin);
sharedPreferences = getSharedPreferences(PREFER_NAME, Context.MODE_PRIVATE);
// Login button click event
buttonLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// Get username, password from EditText
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
// Validate if username, password is filled
if(username.trim().length() > 0 && password.trim().length() > 0){
String uName = null;
String uPassword =null;
if (sharedPreferences.contains("Name"))
{
uName = sharedPreferences.getString("Name", "");
}
if (sharedPreferences.contains("txtPassword"))
{
uPassword = sharedPreferences.getString("txtPassword", "");
}
// Object uName = null;
// Object uEmail = null;
if(username.equals(uName) && password.equals(uPassword)){
session.createUserLoginSession(uName,
uPassword);
// Starting MainActivity
Intent i = new Intent(getApplicationContext(),MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = new MenuInflater(this);
inflater.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.menu1:
Intent intent1 = new Intent(this, Login.class);
this.startActivity(intent1);
break;
case R.id.menu2:
Intent intent2 = new Intent(this, MainActivity.class);
this.startActivity(intent2);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
UserSession.java
package com.example.tripmanager;
import java.util.HashMap;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class UserSession {
// Shared Preferences reference
SharedPreferences pref;
// Editor reference for Shared preferences
Editor editor;
// Context
Context _context;
// Shared preferences mode
int PRIVATE_MODE = 0;
// Shared preferences file name
public static final String PREFER_NAME = "Reg";
// All Shared Preferences Keys
public static final String IS_USER_LOGIN = "IsUserLoggedIn";
// User name (make variable public to access from outside)
public static final String KEY_NAME = "Name";
// Email address (make variable public to access from outside)
public static final String KEY_EMAIL = "Email";
// password
public static final String KEY_PASSWORD = "txtPassword";
// Constructor
public UserSession(Context context){
this._context = context;
pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
//Create login session
public void createUserLoginSession(String uName, String uPassword){
// Storing login value as TRUE
editor.putBoolean(IS_USER_LOGIN, true);
// Storing name in preferences
editor.putString(KEY_NAME, uName);
// Storing email in preferences
editor.putString(KEY_EMAIL, uPassword);
// commit changes
editor.commit();
}
/**
* Check login method will check user login status
* If false it will redirect user to login page
* Else do anything
* */
public boolean checkLogin(){
// Check login status
if(!this.isUserLoggedIn()){
// user is not logged in redirect him to Login Activity
Intent i = new Intent(_context, Login.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;
}
/**
* Get stored session data
* */
public HashMap<String, String> getUserDetails(){
//Use hashmap to store user credentials
HashMap<String, String> user = new HashMap<String, String>();
// user name
user.put(KEY_NAME, pref.getString(KEY_NAME, null));
// user email id
user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null));
// return user
return user;
}
/**
* Clear session details
* */
public void logoutUser(){
// Clearing all user data from Shared Preferences
editor.clear();
editor.commit();
// After logout redirect user to MainActivity
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);
}
// Check for login
public boolean isUserLoggedIn(){
return pref.getBoolean(IS_USER_LOGIN, false);
}
}
The problem here is you haven't called the checkLogin() function you have created in the UserSession.java class into the Login.java. Bcz of which the login status is not being checked. Add this in your Login.java:
if(session.checkLogin()){
val i=Intent(this,MainActivity::class.java)
startActivity(i)
}
else{
setContentView(R.layout.activity_login)
}
And this to your UserSession class as an else statement to the if(!isUserLoggedIn):
else {
val i1=Intent(_context, MainActivity::class.java)
_context.startActivity(i1)
}
Then return false as you did before.
This code is in Kotlin
This code working in my project,must try it
Use this code after login validation to store login value
String Username = textInputEditTextEmail.getText().toString();
String Password = textInputEditTextPassword.getText().toString();
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("Registered", true);
editor.putString("Username", Username);
editor.putString("Password", Password);
editor.apply();
Create new empty activity and copy this code
Boolean Registered;
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
Registered = sharedPref.getBoolean("Registered", false);
if (!Registered)
{
startActivity(new Intent(this,Splash.class));
}else {
startActivity(new Intent(this,MainActivity.class));
}
In Menifest file copy the intent-filter code in newly created empty file for initial access.
For Logout, Create any button copy this code in click on listener
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.commit();
Intent i = new Intent(MainActivity.this,Login.class);
startActivity(i);