Android remember me in log in activity

When you create an application that requires the user to log in, you will need to implement remember me feature so that the user won't enter user name and password again to enter the main interface of the application. In Android, you can use SharedPreferences to store the log in information. Data stored in the SharedPreferences is not removed by default although you exit the application. In this tip, I will show to you how to store log in information in the SharedPreferences and clear the information from the SharedPreferences.


Now you need to create a new Android project. Then modify the activity_main.xml file to add one two EditText, one CheckBox, and one button. One EditText is for imputing user and another EditText allows password input. With the CheckBox, the user can check to remember username and password. The button is pushed to validate the log in information.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".MainActivity" >
  <EditText
     android:id="@+id/txt_user"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="User name"
     android:inputType="text"
      android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
      />

   <EditText
     android:id="@+id/txt_pwd"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:hint="Password"
     android:inputType="textPassword"
      android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
     />
<CheckBox
android:id="@+id/ch_rememberme"
android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="Remember me"
     android:layout_marginLeft="10dp"
     android:layout_marginRight="10dp"
     />
   <Button
      android:id="@+id/btlogin"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:onClick="doLogin"
      android:layout_gravity="center"
      android:text="Log in"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:textColor="#ffffff"
      />  
</LinearLayout>


In the MainActivity class you need to write code to validate the login information, save the information in SharedPreferences, read data from SharedPreferences, and open another activity (log out activity). You read data from SharedPreferences to determine that the user successfully logged in and requested to remember his/her log in information and hence redirect the user to to log out activity.

  package com.example.andtip;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

public static String PREFS_NAME="mypre";
public static String PREF_USERNAME="username";
public static String PREF_PASSWORD="password";
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
    
      }


   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
     getMenuInflater().inflate(R.menu.main, menu);
  
  

return true;
    
   }
  
   public void onStart(){
   super.onStart();
   //read username and password from SharedPreferences
   getUser();
   }
  
   public void doLogin(View view){
    EditText txtuser=(EditText)findViewById(R.id.txt_user);
    EditText txtpwd=(EditText)findViewById(R.id.txt_pwd);
    String username="myusername";
    String password="mypassword";
     if(txtuser.getText().toString().equals(username) && txtpwd.getText().toString().equals(password)){
       CheckBox ch=(CheckBox)findViewById(R.id.ch_rememberme);
      if(ch.isChecked())
        rememberMe(username,password); //save username and password
//show logout activity
    showLogout(username);

   }
   else{
   Toast.makeText(this, "Invalid username or password",Toast.LENGTH_LONG).show();
   }
     

   }
  
   public void getUser(){
   SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);  
   String username = pref.getString(PREF_USERNAME, null);
   String password = pref.getString(PREF_PASSWORD, null);

   if (username != null || password != null) {
      //directly show logout form
   showLogout(username);
   }
   }

   public void rememberMe(String user, String password){
   //save username and password in SharedPreferences
   getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
     .edit()
     .putString(PREF_USERNAME,user)
     .putString(PREF_PASSWORD,password)
     .commit();
  }
  
   public void showLogout(String username){
   //display log out activity
Intent intent=new Intent(this, LogoutActivity.class);
intent.putExtra("user",username);
startActivity(intent);
}


  
}


When you create the new project, Android creates only one activity (MainActivity activity) for you. Now you need to create another activity - log out activity. You can create an activity by selecting File->New->Other->Android->Android Activity. When the New activity dialog asks you to enter the name of the activity, simply type LogoutActivity. The log out activity shows a welcome message and a button to log out the user. You need to modify the activity_logout.xml file to add one TextView and one Button as shown below.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingBottom="@dimen/activity_vertical_margin"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   tools:context=".LogoutActivity" >
  
    <TextView
     android:id="@+id/txtuser"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_marginBottom="20dip"
     />

   <Button
      android:id="@+id/btlogout"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:onClick="logout"
     android:text="Log out"
     android:layout_below="@+id/txtuser"
     />

</RelativeLayout>


You will write more code in the LogoutActivity class to get user name from the previous activity, show the user name in the TextView, and clear log in information from SharedPreferences when the log out button is pushed. Here is the content of the LogoutActivity class.

  package com.example.andtip;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class LogoutActivity extends Activity {

String user;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logout);
//get username sent from the log in activity
Intent intent=getIntent();
Bundle b=intent.getExtras();
user=b.getString("user");
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logout, menu);
return true;
}

public void onStart(){
super.onStart();
TextView view=(TextView)findViewById(R.id.txtuser);
view.setText("Welcome "+user);
}


public void logout(View view){
SharedPreferences sharedPrefs =getSharedPreferences(MainActivity.PREFS_NAME,MODE_PRIVATE);
   Editor editor = sharedPrefs.edit();
   editor.clear();
   editor.commit();
   user="";
   //show login form
   Intent intent=new Intent(this, MainActivity.class);
startActivity(intent);
}

}




Android-remember-me-in-log-in-activity

Posted by: Dara | post date: 05-19-2014 | Subject: Android Apps Development

write programming tip



This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.