title: Android login/registration with shared preferences
body: <p>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 in order to save basic information and the eventually travels that the user booked. I can't find an example on the web that combine the registration and login forms. I wrote this code but it's not working. It doesn't show any error. I think what I wrote it's not logic. I'd like to register first and login with the information I gave in the registration form. Thank you for your help.</p>
  
  <p>This is my Login.java:</p>
  
  <pre><code>package com.example.trip;
  
  import android.content.Context;
  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;
  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 = null;
  
  Button buttonLogin;
  
  EditText txtUsername, txtPassword;
  
  // User Session Manager Class
  UserSession session;
  
  @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() &gt; 0 &amp;&amp; password.trim().length() &gt; 0){
  
                  if (SharedPreferences.contains("name"))
                    {
                       String uName = (SharedPreferences).getString("name", "");
  
                    }
  
                    if (SharedPreferences.contains("email"))
                    {
                       String uEmail = (SharedPreferences).getString("email", "");
  
                    }
  
                              Object uName = null;
                              Object uEmail = null;
                              if(username.equals(uName) &amp;&amp; password.equals(uEmail)){
  
                                  session.createUserLoginSession(uName, 
                                     uEmail);
  
                                  // 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&amp;
                                  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.MENU_1:
              Intent intent1 = new Intent(this, Login.class);
              this.startActivity(intent1);
              break;
          case R.id.MENU_2:
              Intent intent2 = new Intent(this, MainActivity.class);
              this.startActivity(intent2);
          break;
          default:
              return super.onOptionsItemSelected(item);
          }
  
          return true;
      }       
  }
  </code></pre>
  
  <p>This is the UserSession.java:</p>
  
  <pre><code>package com.example.trip;
  
  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 = "AndroidExamplePref";
  
  // 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";
  
  // Constructor
  public UserSession(Context context){
      this._context = context;
      pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
      editor = pref.edit();
  }
  
  //Create login session
  public void createUserLoginSession(Object uName, Object uEmail){
      // Storing login value as TRUE
      editor.putBoolean(IS_USER_LOGIN, true);
  
      // Storing name in preferences
      editor.putString(KEY_NAME, (String) uName);
  
      // Storing email in preferences
      editor.putString(KEY_EMAIL, (String) uEmail);
  
      // 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&lt;String, String&gt; getUserDetails(){
  
      //Use hashmap to store user credentials
      HashMap&lt;String, String&gt; user = new HashMap&lt;String, String&gt;();
  
      // 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);
  }
  }
  </code></pre>
  
  <p>This is the MainActivity.java:</p>
  
  <pre><code>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.MENU_1:
          Intent intent1 = new Intent(this, Login.class);
          this.startActivity(intent1);
          break;
      case R.id.MENU_2:
          Intent intent2 = new Intent(this, MainActivity.class);
          this.startActivity(intent2);
      break;
      default:
          return super.onOptionsItemSelected(item);
      }
  
      return true;
  }
  }
  </code></pre>
  
  <p>This is my Reg.java:</p>
  
  <pre><code>package com.example.trip;
  
  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;
  import android.view.View.OnClickListener;
  
  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 = 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()&lt;=0){
          Toast.makeText(Reg.this, "Enter name", Toast.LENGTH_SHORT).show();
      }
      else if( txtEmail.getText().length()&lt;=0){
          Toast.makeText(Reg.this, "Enter email", Toast.LENGTH_SHORT).show();
      }
      else if( txtPassword.getText().length()&lt;=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.MENU_1:
              Intent intent1 = new Intent(this, Login.class);
              this.startActivity(intent1);
              break;
          case R.id.MENU_2:
              Intent intent2 = new Intent(this, MainActivity.class);
              this.startActivity(intent2);
          break;
          default:
              return super.onOptionsItemSelected(item);
          }
  
          return true;
      }
   }
  </code></pre>
  
  <p>The XML code of the MainActivity:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:gravity="top"
      android:shrinkColumns="0"
      android:stretchColumns="1" &gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/destinazione" /&gt;
  
          &lt;EditText
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="text" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/checkin" /&gt;
  
          &lt;EditText
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="date" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/checkout" /&gt;
  
          &lt;EditText
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="date" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/viaggiatori" /&gt;
  
          &lt;EditText
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="number" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/stelle" /&gt;
  
          &lt;Spinner
              android:id="@+id/spinner"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:entries="@array/stelle"/&gt;
      &lt;/TableRow&gt;
  
      &lt;Button
          android:id="@+id/buttonFind"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/buttonFind" /&gt;
  
    &lt;/TableLayout&gt;
  </code></pre>
  
  <p>The XML code for the login form:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="top"
  android:shrinkColumns="0"
  android:stretchColumns="1" &gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/txtUsername" /&gt;
  
          &lt;EditText
              android:id="@+id/txtUsername"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="text" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/txtPassword" /&gt;
  
          &lt;EditText
              android:id="@+id/txtPassword"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="textPassword" /&gt;
      &lt;/TableRow&gt;
  
      &lt;Button
          android:id="@+id/buttonLogin"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/buttonLogin" /&gt;
  
      &lt;Button
          android:id="@+id/buttonReg"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/buttonReg" /&gt;
  
   &lt;/TableLayout&gt;
  </code></pre>
  
  <p>This is the XML code for the registration form:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt;
  &lt;TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:gravity="top"
  android:shrinkColumns="0"
  android:stretchColumns="1" &gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/Name" /&gt;
  
          &lt;EditText
              android:id="@+id/Name"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="text" /&gt;
      &lt;/TableRow&gt;
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/Email" /&gt;
  
          &lt;EditText
              android:id="@+id/Email"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="textEmailAddress" /&gt;
      &lt;/TableRow&gt;
  
  
      &lt;TableRow
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:gravity="fill_horizontal|center_vertical" &gt;
  
          &lt;TextView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:gravity="fill_horizontal|center_vertical"
              android:text="@string/txtPassword" /&gt;
  
          &lt;EditText
              android:id="@+id/txtPassword"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:inputType="textPassword" /&gt;
      &lt;/TableRow&gt;
  
      &lt;Button
          android:id="@+id/buttonReg2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/buttonReg2" /&gt;
  
   &lt;/TableLayout&gt;
  </code></pre>