This is a continuation post on explaining android connection to MS SQL Database using jtds jar library. This post is about How to create Login screen in android using SQL Database. For connecting Android with MySQL server, see this post.
Download Source code.
In previously created signup.xml file we will add new button for Login process. User can use this after successful signup process.
Changes are as below:
res > layout > signup.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/lvparent" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="5dp"> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="50dp" android:orientation="horizontal" android:padding="5dp"> <ImageView android:layout_width="50dp" android:layout_height="50dp" android:layout_gravity="center_vertical" android:src="@drawable/user" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_marginRight="5dp" android:fontFamily="sans-serif-black" android:gravity="center_horizontal" android:text="USER SIGN UP" android:textColor="@color/colorPrimary" android:textSize="25sp" /> </LinearLayout> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:gravity="start" android:text="Enter Email Address" android:textSize="16sp" /> <EditText android:id="@+id/edtEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/myedittextbg" android:hint="Email Address" android:padding="5dp" android:textColor="#2d3436" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:gravity="start" android:text="Password" android:textSize="16sp" /> <EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/myedittextbg" android:hint="Enter Password" android:inputType="textPassword" android:padding="5dp" android:textColor="#2d3436" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="15dp" android:gravity="start" android:text="Confirm Password" android:textSize="16sp" /> <EditText android:id="@+id/edtConfirmPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/myedittextbg" android:hint="Confirm Password" android:inputType="textPassword" android:padding="5dp" android:textColor="#2d3436" /> <Button android:id="@+id/btnSignUp" android:layout_width="250dp" android:layout_height="34dp" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:background="@color/colorPrimary" android:text="SIGN UP" android:textColor="#fff" /> <Button android:id="@+id/btnSignIn" android:layout_width="250dp" android:layout_height="34dp" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:background="@color/colorLightGray" android:onClick="Login" android:text="Login" android:textColor="#000" /> <ProgressBar android:id="@+id/pbbar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> </LinearLayout>
Now edit the signup.java file as below:
signup.java:
package com.app.myapplication; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.content.Intent; import android.media.tv.TvContract; import android.os.AsyncTask; import android.os.Bundle; import android.os.StrictMode; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.Spinner; import android.widget.Toast; public class signup extends AppCompatActivity { EditText edtEmailAddress, edtPassword, edtConfirmPassword; Button btnSignUp; ProgressBar progressBar; LinearLayout lvparent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.signup); edtEmailAddress = findViewById(R.id.edtEmailAddress); edtPassword = findViewById(R.id.edtPassword); edtConfirmPassword = findViewById(R.id.edtConfirmPassword); btnSignUp = findViewById(R.id.btnSignUp); progressBar = findViewById(R.id.pbbar); lvparent = findViewById(R.id.lvparent); this.setTitle("User SignUp"); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isEmpty(edtEmailAddress.getText().toString()) || isEmpty(edtPassword.getText().toString()) || isEmpty(edtConfirmPassword.getText().toString())) ShowSnackBar("Please enter all fields"); else if (!edtPassword.getText().toString().equals(edtConfirmPassword.getText().toString())) ShowSnackBar("Password does not match"); else { AddUsers addUsers = new AddUsers(); addUsers.execute(""); } } }); } public void ShowSnackBar(String message) { Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG) .setAction("CLOSE", new View.OnClickListener() { @Override public void onClick(View view) { } }) .setActionTextColor(getResources().getColor(android.R.color.holo_red_light)) .show(); } public Boolean isEmpty(String strValue) { if (strValue == null || strValue.trim().equals((""))) return true; else return false; } private class AddUsers extends AsyncTask<String, Void, String> { String emailId, password; @Override protected void onPreExecute() { super.onPreExecute(); emailId = edtEmailAddress.getText().toString(); password = edtPassword.getText().toString(); progressBar.setVisibility(View.VISIBLE); btnSignUp.setVisibility(View.GONE); } @Override protected String doInBackground(String... params) { try { ConnectionHelper con = new ConnectionHelper(); Connection connect = ConnectionHelper.CONN(); String queryStmt = "Insert into tblUsers " + " (UserId,Password,UserRole) values " + "('" + emailId + "','" + password + "','User')"; PreparedStatement preparedStatement = connect .prepareStatement(queryStmt); preparedStatement.executeUpdate(); preparedStatement.close(); return "Added successfully"; } catch (SQLException e) { e.printStackTrace(); return e.getMessage().toString(); } catch (Exception e) { return e.getMessage().toString(); } } @Override protected void onPostExecute(String result) { //Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show(); ShowSnackBar(result); progressBar.setVisibility(View.GONE); btnSignUp.setVisibility(View.VISIBLE); if (result.equals("Added successfully")) { // Clear(); } } } public void Login(View v) { Intent i = new Intent(signup.this, Login.class); startActivity(i); } }
The Login method will call our Login page.
Add two new layout file with names:
- login.xml
- activity_main.xml
in the layout folder and edit them as below.
First, please add two new colors in the colors.xml file as below:
res > values > colors.xml:
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="colorPrimary">#1595e4</color> <color name="colorPrimaryDark">#023250</color> <color name="colorAccent">#D81B60</color> <color name="colorLightGray">#CFCFCF</color> </resources>
res > layout > login.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/lvparent" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:gravity="center_horizontal" android:text="USER LOGIN" android:textSize="25sp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:text="Enter your UserID" android:textSize="16sp" /> <EditText android:id="@+id/edtEmailAddress" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/myedittextbg" android:hint="Enter your UserID" android:padding="5dp" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:text="Password" android:textSize="16sp" /> <EditText android:id="@+id/edtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:background="@drawable/myedittextbg" android:hint="Enter your Password" android:padding="5dp" /> <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="34dp" android:layout_gravity="center_horizontal" android:layout_marginTop="20dp" android:padding="5dp"emai android:background="@color/colorLightGray" android:text="LOGIN" android:onClick="DoLogin"/> <ProgressBar android:id="@+id/progressBar" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> </LinearLayout>
This file will be used for performing the login process.
res > layout > activity_main.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/lblEmailAddress" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
This layout will be shown after successful login process to the user with email address from SharedPreferences.
Now let’s create methods for performing connection with MS SQL server database and login in the users.
Create a new java class file in your project with name Login.java and edit it as below:
Login.java:
package com.app.myapplication; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ProgressBar; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class Login extends AppCompatActivity { EditText edtEmailAddress, edtPassword; Button btnLogin; ProgressBar progressBar; LinearLayout lvparent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login); edtEmailAddress = findViewById(R.id.edtEmailAddress); edtPassword = findViewById(R.id.edtPassword); btnLogin = findViewById(R.id.btnLogin); lvparent = findViewById(R.id.lvparent); progressBar = findViewById(R.id.progressBar); } private class DoLoginForUser extends AsyncTask<String, Void, String> { String emailId, password; @Override protected void onPreExecute() { super.onPreExecute(); emailId = edtEmailAddress.getText().toString(); password = edtPassword.getText().toString(); progressBar.setVisibility(View.VISIBLE); btnLogin.setVisibility(View.GONE); } @Override protected String doInBackground(String... params) { try { ConnectionHelper con = new ConnectionHelper(); Connection connect = ConnectionHelper.CONN(); String query = "Select * from tblUsers where UserId='" + emailId + "'"; PreparedStatement ps = connect.prepareStatement(query); Log.e("query",query); ResultSet rs = ps.executeQuery(); if (rs.next()) { String passcode = rs.getString("password"); connect.close(); rs.close(); ps.close(); if (passcode != null && !passcode.trim().equals("") && passcode.equals(password)) return "success"; else return "Invalid Credentials"; } else return "User does not exists."; } catch (SQLException e) { return "Error:" + e.getMessage().toString(); } catch (Exception e) { return "Error:" + e.getMessage().toString(); } } @Override protected void onPostExecute(String result) { //Toast.makeText(signup.this, result, Toast.LENGTH_SHORT).show(); ShowSnackBar(result); progressBar.setVisibility(View.GONE); btnLogin.setVisibility(View.VISIBLE); if (result.equals("success")) { SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("email",edtEmailAddress.getText().toString()); editor.commit(); Intent i = new Intent(Login.this, MainActivity.class); startActivity(i); } else { ShowSnackBar(result); } } } public void ShowSnackBar(String message) { Snackbar.make(lvparent, message, Snackbar.LENGTH_LONG) .setAction("CLOSE", new View.OnClickListener() { @Override public void onClick(View view) { } }) .setActionTextColor(getResources().getColor(android.R.color.holo_red_light)) .show(); } public void DoLogin(View v) { DoLoginForUser login = new DoLoginForUser(); login.execute(""); } }
The DoLoginForUser async process will be called on clicking the login button. It will check for the emailId in the sql database table using jtds ResultSets. Upon getting data from sql database, we are comparing the password if it matches or not. On success, we will store the user email address from sql database in Android SharedPreferences and move on to next activity. Now create a new class file with MainActivity.java and edit it as below:
MainActivity.java:
package com.app.myapplication; import android.content.SharedPreferences; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends AppCompatActivity { TextView lblEmail; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lblEmail = findViewById(R.id.lblEmailAddress); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("userdetails",0); lblEmail.setText(sharedPreferences.getString("email","0")); } }
This file will simply display email address of the user stored in Android SharedPreferences at Login task.
Please edit your AndroidManifest.xml file and add newly created activities name in android manifest file or else you will get run time exception.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.app.myapplication"> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".signup" android:screenOrientation="portrait" android:label="@string/app_name" android:theme="@style/AppTheme"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainActivity" android:screenOrientation="portrait" android:label="@string/app_dashboard" /> <activity android:name=".Login" android:screenOrientation="portrait" android:label="@string/app_login" /> </application> </manifest>
Download Source code.
Also see related to Android connection with MS SQL database:
- Using stored procedure in Android from MS SQL Server.
- Bind Android Spinner using MS SQL Database.
- Android GridView using MS SQL Database.
- Filling data in Android Listview using MS SQL Database.
- Storing Images in MS SQL database in Base64 string values using Android
- Retrieving Images from MS SQL Database in Android.
- Storing images using ASP.NET webservice in MS SQL database from Android
- Android Login Application using MS SQL Server and SharedPreferences