Friday 27 October 2017

Connect Android With SQL Server

Requirements for the App

1) Android Studio. 
2) SQL Server. 
3) Firewall must allow to connect to database. (or turn off firewall from control pannel) 
4) Download and add latest version of jtds jar file and include it in your project. See how to include jtds jar file to your project HERE.
5) You need to change database ip address, user name, database name and password in the MainActivity.java file below at end. 6) Must also modify the query string in MainActivity.java file below at end.

Open your gradle module App and add the following

build.gradle (Module App)
dependencies {
 compile fileTree(dir: 'libs', include: ['*.jar'])
 compile 'com.android.support:appcompat-v7:23.1.1'
 compile project(':jtds-1.2.7') // Add this line to your dependencies
 }

Now, Open your activity_main.xml and add the following code

activity_main.xml
<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"
        tools:context=".MainActivity">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:id="@+id/editText"
        android:hint="Enter Name Here..."
        android:layout_marginTop="144dp"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:inputType="textPassword"
        android:hint="Enter Pass Here..."
        android:ems="10"
        android:id="@+id/editText2"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="70dp"
        android:text="Login"
        android:id="@+id/button"
        android:layout_marginTop="40dp"
        android:layout_below="@+id/editText2"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="My Login App"
        android:gravity="center_horizontal"
        android:textSize="34sp"
        android:id="@+id/textView"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="57dp" />
</RelativeLayout>
                

Open your AndroidManifest.xml file and add the following permission

AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />

Now, Open your activity_main.xml and add the following code

You need to change the database credentials and modify query string in this file somewhere below.
MainActivity.java
 import android.annotation.SuppressLint;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.StrictMode;
    import android.support.v7.app.ActionBarActivity;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.ProgressBar;
    import android.widget.Toast;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Statement;
/*
        This source code could be used for academic purposes only. Posting on other websites or blogs is only allowed with a dofollow link to the orignal content.
    */

    public class MainActivity extends ActionBarActivity
    {
        // Declaring layout button, edit texts
        Button login;
        EditText username,password;
        ProgressBar progressBar;
        // End Declaring layout button, edit texts

        // Declaring connection variables
        Connection con;
        String un,pass,db,ip;
        //End Declaring connection variables
@Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            // Getting values from button, texts and progress bar
            login = (Button) findViewById(R.id.button);
            username = (EditText) findViewById(R.id.editText);
            password = (EditText) findViewById(R.id.editText2);
            progressBar = (ProgressBar) findViewById(R.id.progressBar);
            // End Getting values from button, texts and progress bar

            // Declaring Server ip, username, database name and password
            ip = "your server ip here";
            db = "your database name here";
            un = "your username for that database here";
            pass = "your password for that database here";
            // Declaring Server ip, username, database name and password

            // Setting up the function when button login is clicked
            login.setOnClickListener(new View.OnClickListener()
            { @Override
                public void onClick(View v)
                {
                    CheckLogin checkLogin = new CheckLogin();// this is the Asynctask, which is used to process in background to reduce load on app process
                    checkLogin.execute("");
                }
            });
            //End Setting up the function when button login is clicked
        }

        public class CheckLogin extends AsyncTask<String,String,String>
        {
            String z = "";
            Boolean isSuccess = false;

            @Override
            protected void onPreExecute()
            {
                progressBar.setVisibility(View.VISIBLE);
            }
                 @Override
            protected void onPostExecute(String r)
            {
                progressBar.setVisibility(View.GONE);
                Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
                if(isSuccess)
                {
                    Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_LONG).show();
                    //finish();
                }
            } 
 @Override
            protected String doInBackground(String... params)
            {
                String usernam = username.getText().toString();
                String passwordd = password.getText().toString();
                if(usernam.trim().equals("")|| passwordd.trim().equals(""))
                    z = "Please enter Username and Password";
                else
                {
                    try
                    {
                        con = connectionclass(un, pass, db, ip);        // Connect to database
                        if (con == null)
                        {
                            z = "Check Your Internet Access!";
                        }
                        else
                        {
                             // Change below query according to your own database.
                            String query = "select * from login where user_name= '" + usernam.toString() + "' and pass_word = '"+ passwordd.toString() +"'  ";
                            Statement stmt = con.createStatement();
                            ResultSet rs = stmt.executeQuery(query);
                            if(rs.next())
                            {
                                z = "Login successful";
                                isSuccess=true;
                                con.close();
                            }
                            else
                            {
                                z = "Invalid Credentials!";
                                isSuccess = false;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        isSuccess = false;
                        z = ex.getMessage();
                    }
                }
                return z;
}
        }


        @SuppressLint("NewApi")
        public Connection connectionclass(String user, String password, String database, String server)
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            Connection connection = null;
            String ConnectionURL = null;
            try
            {
                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
                connection = DriverManager.getConnection(ConnectionURL);
            }
            catch (SQLException se)
            {
                Log.e("error here 1 : ", se.getMessage());
            }
catch (ClassNotFoundException e)
            {
                Log.e("error here 2 : ", e.getMessage());
            }
            catch (Exception e)
            {
                Log.e("error here 3 : ", e.getMessage());
            }
            return connection;
        }
    }

Screenshots of the App :


android login app android login app seotoolzz
android login app demo android login app

0 comments: