Android Login using
Session Manager
In this tutorial you can see how
to make login registration using session manager in android. You can use this
session throughout your app and provide shared preference in your app.
If you are following my previous login
registration tutorial, then you have to change it to session manager very
easily.
Add this in your gradle build
file.
Build.gradle
compile 'com.loopj.android:android-async-http:1.4.5' compile files("${android.getSdkDirectory().getAbsolutePath()}" + File.separator + "platforms" + File.separator + "android-23" + File.separator + "optional" + File.separator + "org.apache.http.legacy.jar")
AndroidManifest.xml
<?xml version="1.0"
encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loginwithsession">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Registration" />
<activity android:name=".Welcome"></activity>
</application>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.loginwithsession">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Registration" />
<activity android:name=".Welcome"></activity>
</application>
</manifest>
MainActivity.java
package com.loginwithsession; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { private EditText editTextUserName; private EditText editTextPassword; Button Register; public static final String USER_NAME = "USERNAME"; String username; String password; UserSessionManager session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); session = new UserSessionManager(getApplicationContext()); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show(); if(session.isUserLoggedIn() == true){ Intent intent = new Intent(getApplicationContext(),Welcome.class); startActivity(intent); } editTextUserName = (EditText) findViewById(R.id.editTextUserName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); Register =(Button)findViewById(R.id.register); Register.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, Registration.class); startActivity(intent); } }); } public void invokeLogin(View view){ username = editTextUserName.getText().toString(); password = editTextPassword.getText().toString(); login(username,password); } private void login(final String username, final String password) { class LoginAsync extends AsyncTask<String, Void, String>{ private Dialog loadingDialog; @Override protected void onPreExecute() { super.onPreExecute(); loadingDialog = ProgressDialog.show(MainActivity.this, "Please wait", "Loading..."); } @Override protected String doInBackground(String... params) { String uname = params[0]; String pass = params[1]; InputStream is = null; List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); nameValuePairs.add(new BasicNameValuePair("username", uname)); nameValuePairs.add(new BasicNameValuePair("password", pass)); String result = null; try{ HttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost("http://compliments.esy.es/loginm.php"); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } result = sb.toString(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(String result){ String s = result.trim(); loadingDialog.dismiss(); if(s.equalsIgnoreCase("success")){ session.createUserLoginSession(username, password); Intent i = new Intent(getApplicationContext(), Welcome.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(); Toast.makeText(getApplicationContext(), "success", Toast.LENGTH_LONG).show(); }else { Toast.makeText(getApplicationContext(), "Invalid User Name or Password", Toast.LENGTH_LONG).show(); } } } LoginAsync la = new LoginAsync(); la.execute(username, password); } }
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <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:paddingLeft="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="User Name" android:id="@+id/textView" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/editTextUserName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Password" android:id="@+id/textView2" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:ems="10" android:id="@+id/editTextPassword" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Login" android:onClick="invokeLogin" android:id="@+id/button" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Register" android:id="@+id/register" android:layout_gravity="center_horizontal" /> </LinearLayout>
Regitration.java
package com.loginwithsession; import android.app.ProgressDialog; import android.content.Intent; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Registration extends AppCompatActivity implements View.OnClickListener{ private EditText editTextName; private EditText editTextUsername; private EditText editTextPassword; private EditText editTextEmail; private Button buttonRegister; private static final String REGISTER_URL = "http://compliments.esy.es/register.php"; UserSessionManager session; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); session = new UserSessionManager(getApplicationContext()); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show(); if(session.isUserLoggedIn() == true){ Intent intent = new Intent(getApplicationContext(),Welcome.class); startActivity(intent); } editTextName = (EditText) findViewById(R.id.editTextName); editTextUsername = (EditText) findViewById(R.id.editTextUserName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); editTextEmail = (EditText) findViewById(R.id.editTextEmail); buttonRegister = (Button) findViewById(R.id.buttonRegister); buttonRegister.setOnClickListener(this); } @Override public void onClick(View v) { if(v == buttonRegister){ registerUser(); } } private void registerUser() { String name = editTextName.getText().toString().trim().toLowerCase(); String username = editTextUsername.getText().toString().trim().toLowerCase(); String password = editTextPassword.getText().toString().trim().toLowerCase(); String email = editTextEmail.getText().toString().trim().toLowerCase(); register(name,username,password,email); } private void register(String name, String username, String password, String email) { String urlSuffix = "?name="+name+"&username="+username+"&password="+password+"&email="+email; class RegisterUser extends AsyncTask<String, Void, String>{ ProgressDialog loading; @Override protected void onPreExecute() { super.onPreExecute(); loading = ProgressDialog.show(Registration.this, "Please Wait",null, true, true); } @Override protected void onPostExecute(String s) { super.onPostExecute(s); loading.dismiss(); finish(); Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } @Override protected String doInBackground(String... params) { String s = params[0]; BufferedReader bufferedReader = null; try { URL url = new URL(REGISTER_URL+s); HttpURLConnection con = (HttpURLConnection) url.openConnection(); bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream())); String result; result = bufferedReader.readLine(); return result; }catch(Exception e){ return null; } } } RegisterUser ru = new RegisterUser(); ru.execute(urlSuffix); } }
activity_registration.xml
<?xml version="1.0" encoding="utf-8"?> <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:paddingLeft="@dimen/activity_horizontal_margin" android:orientation="vertical" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".Registration"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="enter_name" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editTextName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="choose_username" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/editTextUserName" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="choose_password" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textPassword" android:id="@+id/editTextPassword" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="enter_email" /> <EditText android:layout_width="fill_parent" android:layout_height="wrap_content" android:inputType="textEmailAddress" android:id="@+id/editTextEmail" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="button_register" android:id="@+id/buttonRegister" /> </LinearLayout>
UserSessionManager.java
package com.loginwithsession; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import java.util.HashMap; public class UserSessionManager { // Shared Preferences reference SharedPreferences pref; // Editor reference for Shared preferences Editor editor; // Context Context _context; // Shared pref mode int PRIVATE_MODE = 0; // Sharedpref file name private static final String PREFER_NAME = "AndroidExamplePref"; // All Shared Preferences Keys private static final String IS_USER_LOGIN = "IsUserLoggedIn"; // User name (make variable public to access from outside) public static final String KEY_NAME = "username"; // Email address (make variable public to access from outside) public static final String KEY_EMAIL = "password"; // Constructor public UserSessionManager(Context context){ this._context = context; pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); editor = pref.edit(); } //Create login session public void createUserLoginSession(String name, String email){ // Storing login value as TRUE editor.putBoolean(IS_USER_LOGIN, true); // Storing name in pref editor.putString(KEY_NAME, name); // Storing email in pref editor.putString(KEY_EMAIL, email); // 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, MainActivity.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 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); } // Check for login public boolean isUserLoggedIn(){ return pref.getBoolean(IS_USER_LOGIN, false); } }
Welcome.java
package com.loginwithsession; import java.util.HashMap; import android.app.Activity; import android.os.Bundle; import android.text.Html; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; public class Welcome extends Activity { // User Session Manager Class UserSessionManager session; // Button Logout Button btnLogout; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_welcome); // Session class instance session = new UserSessionManager(getApplicationContext()); TextView Name = (TextView) findViewById(R.id.lblName); // Button logout btnLogout = (Button) findViewById(R.id.btnLogout); Toast.makeText(getApplicationContext(), "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show(); // Check user login (this is the important point) // If User is not logged in , This will redirect user to LoginActivity // and finish current activity from activity stack. if(session.checkLogin()) finish(); // get user data from session HashMap<String, String> user = session.getUserDetails(); // get name String name = user.get(UserSessionManager.KEY_NAME); // Show user data on activity Name.setText(Html.fromHtml("Name: <b>" + name + "</b>")); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Clear the User session data // and redirect user to LoginActivity session.logoutUser(); } }); } }
activity_welcome.xml
<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:padding="10dip"> <TextView android:id="@+id/lblName" android:layout_width="fill_parent" android:layout_height="wrap_content" android:singleLine="true" android:layout_marginTop="40dip" android:layout_marginBottom="10dip"/> <Button android:id="@+id/btnLogout" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Logout"/> </LinearLayout>
No comments:
Post a Comment