Connect Android to MS SQL Database.

This is a continuation of the post on explaining login process using MS SQL Database. This post is about Insert, Update and delete process in the MS SQL database using Android application.

For configuring SQL to connect using IP address in a same local network (or Wifi network), please see this post.

Note : If you haven’t yet seen my first post on login application please do so, as it has the ConnectionClass and Database script and also AndroidManifest file details.

Make a new layout file in the application with name addproducts.xml and edit is as following :

addproducts.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"
 android:orientation="vertical"
 android:background="#282828">

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:layout_alignParentTop="true"
 android:padding="2dp">

 <TextView
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:text="ADD PRODUCTS"
 android:layout_marginTop="7dp"
 android:typeface="sans"
 android:textSize="35sp"
 android:textColor="#ffffff"
 android:gravity="center" />

 <EditText
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_marginTop="10dp"
 android:textColor="#ffffff"
 android:textColorHint="#ffffff"
 android:textStyle="bold"
 android:background="#5d5d5d"
 android:padding="10dp"
 android:hint="PRODUCT NAME"
 android:textSize="20sp"
 android:id="@+id/edtproname" />

 <EditText
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:textSize="16sp"
 android:hint="DESCRIPTION"
 android:textColor="#ffffff"
 android:textColorHint="#ffffff"
 android:textStyle="bold"
 android:background="#5d5d5d"
 android:padding="10dp"
 android:inputType="textMultiLine"
 android:maxLines="3"
 android:minLines="2"
 android:layout_gravity="top|left"
 android:layout_marginTop="5dp"
 android:id="@+id/edtprodesc" />

 <LinearLayout
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:weightSum="3"
 android:layout_marginTop="5dp"
 android:orientation="horizontal">

 <Button
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:background="@drawable/btnbg"
 android:textColor="#ffffff"
 android:textSize="20sp"
 android:layout_margin="2dp"
 android:padding="7dp"
 android:layout_marginTop="10dp"
 android:id="@+id/btnadd"
 android:text="Add" />

 <Button
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:layout_margin="2dp"
 android:background="@drawable/btnbg"
 android:textColor="#ffffff"
 android:textSize="20sp"
 android:padding="7dp"
 android:layout_marginTop="10dp"
 android:id="@+id/btnupdate"
 android:text="Update" />

 <Button
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="1"
 android:background="@drawable/btnbg"
 android:textColor="#ffffff"
 android:textSize="20sp"
 android:layout_margin="2dp"
 android:padding="7dp"
 android:layout_marginTop="10dp"
 android:id="@+id/btndelete"
 android:text="Delete" />
 </LinearLayout>

 <ProgressBar
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="center"
 android:id="@+id/pbbar" />

 <ListView
 android:id="@+id/lstproducts"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:divider="#808080"
 android:layout_marginTop="5dp"
 android:dividerHeight="1dp"
 android:padding="5dp">

 </ListView>
 </LinearLayout>
</RelativeLayout>

Another xml layout file with name lsttemplate.xml and edit it as following :

lsttemplate.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:weightSum="5"
 android:padding="5dp"
android:layout_marginTop="2dp"
 >

 <TextView
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:textColor="#ffffff"
 android:layout_weight="1"
 android:textSize="15sp"
 android:text="1"
 android:id="@+id/lblproid"/>

 <TextView
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="4"
 android:textColor="#ffffff"
 android:textSize="15sp"
 android:text="MOTOROLA"
 android:id="@+id/lblproname"/>


 <TextView
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_weight="0"
 android:textColor="#ffffff"
 android:textSize="0sp"
 android:text="MOTOROLA"
 android:id="@+id/lblprodesc"/>
</LinearLayout>

The first file addproducts.xml is the layout design file and lsttemplate.xml is the layout file for our listview to make up. I hope you find design good.

More on Android and MS SQL :

  1. Filling data in Android Spinner using MS SQL Database.
  2. Using Stored Procedure in Android from MS SQL Server
  3. Filling data in Android GridView using MS SQL Database.
  4. Filling data in Android Listview using MS SQL Database.
  5. Storing Images in MS SQL database in Base64 string values using Android
  6. Retrieving Images from MS SQL Database in Android.
  7. Storing images using ASP.NET webservice in MS SQL database from Android

 

 

Now add a class file in your application with name AddProducts.java

Declare following variables in this class :


    ConnectionClass connectionClass;
    EditText edtproname, edtprodesc;
    Button btnadd,btnupdate,btndelete;
    ProgressBar pbbar;
    ListView lstpro;
    String proid;

In the onCreate initialize this variables :


 super.onCreate(savedInstanceState);
        setContentView(R.layout.addproducts);

        connectionClass = new ConnectionClass();
        edtproname = (EditText) findViewById(R.id.edtproname);
        edtprodesc = (EditText) findViewById(R.id.edtprodesc);
        btnadd = (Button) findViewById(R.id.btnadd);
        btnupdate = (Button) findViewById(R.id.btnupdate);
        btndelete = (Button) findViewById(R.id.btndelete);
        pbbar = (ProgressBar) findViewById(R.id.pbbar);
        pbbar.setVisibility(View.GONE);
        lstpro = (ListView) findViewById(R.id.lstproducts);
        proid = "";

Here I am making four AsyncTask for doing background processes.
First make a AsyncTask task named FillList as following :

AsyncTask task 1 – FillList (to fill the data in listview and click listener of the list):


public class FillList extends AsyncTask<String, String, String> {
        String z = "";

        List<Map<String, String>> prolist  = new ArrayList<Map<String, String>>();

        @Override
        protected void onPreExecute() {

            pbbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r) {

            pbbar.setVisibility(View.GONE);
            Toast.makeText(AddProducts.this, r, Toast.LENGTH_SHORT).show();

            String[] from = { "A", "B", "C" };
            int[] views = { R.id.lblproid, R.id.lblproname,R.id.lblprodesc };
            final SimpleAdapter ADA = new SimpleAdapter(AddProducts.this,
                    prolist, R.layout.lsttemplate, from,
                    views);
            lstpro.setAdapter(ADA);


            lstpro.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View arg1,
                                        int arg2, long arg3) {
                    HashMap<String, Object> obj = (HashMap<String, Object>) ADA
                            .getItem(arg2);
                    proid = (String) obj.get("A");
                    String proname = (String) obj.get("B");
                    String prodesc = (String) obj.get("C");
                    edtprodesc.setText(prodesc);
                    edtproname.setText(proname);
               //     qty.setText(qtys);
                }
            });



        }

        @Override
        protected String doInBackground(String... params) {

            try {
                Connection con = connectionClass.CONN();
                if (con == null) {
                    z = "Error in connection with SQL server";
                } else {
                    String query = "select * from Producttbl";
                    PreparedStatement ps = con.prepareStatement(query);
                    ResultSet rs = ps.executeQuery();

                    ArrayList data1 = new ArrayList();
                    while (rs.next()) {
                        Map<String, String> datanum = new HashMap<String, String>();
                        datanum.put("A", rs.getString("Id"));
                        datanum.put("B", rs.getString("ProName"));
                        datanum.put("C", rs.getString("ProDesc"));
                        prolist.add(datanum);
                    }


                    z = "Success";
                }
            } catch (Exception ex) {
                z = "Error retrieving data from table";

            }
            return z;
        }
    }

Now add onClick Listeners to three buttons :


btnadd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AddPro addPro = new AddPro();
                addPro.execute("");

            }
        });
        btnupdate.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                UpdatePro updatePro = new UpdatePro();
                updatePro.execute("");

            }
        });

        btndelete.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                DeletePro deletePro = new DeletePro();
                deletePro.execute("");

            }
        });

AsyncTask task 2 – AddPro(to add product in our database):


public class AddPro extends AsyncTask<String, String, String> {



        String z = "";
        Boolean isSuccess = false;


        String proname = edtproname.getText().toString();
        String prodesc = edtprodesc.getText().toString();


        @Override
        protected void onPreExecute() {
            pbbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r) {
            pbbar.setVisibility(View.GONE);
            Toast.makeText(AddProducts.this, r, Toast.LENGTH_SHORT).show();
            if(isSuccess==true) {
                FillList fillList = new FillList();
                fillList.execute("");
            }

        }

        @Override
        protected String doInBackground(String... params) {
            if (proname.trim().equals("") || prodesc.trim().equals(""))
                z = "Please enter User Id and Password";
            else {
                try {
                    Connection con = connectionClass.CONN();
                    if (con == null) {
                        z = "Error in connection with SQL server";
                    } else {

                        String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH)
                                .format(Calendar.getInstance().getTime());
                        String query = "insert into Producttbl (ProName,ProDesc,OnDate) values ('" + proname + "','" + prodesc + "','" + dates + "')";
                        PreparedStatement preparedStatement = con.prepareStatement(query);
                        preparedStatement.executeUpdate();
                        z = "Added Successfully";
                        isSuccess = true;
                    }
                } catch (Exception ex) {
                    isSuccess = false;
                    z = "Exceptions";
                }
            }
            return z;
        }
    }

 

AsyncTask task 3 – UpdatePro(to Update a product in our database):


public class UpdatePro extends AsyncTask<String, String, String> {



        String z = "";
        Boolean isSuccess = false;


        String proname = edtproname.getText().toString();
        String prodesc = edtprodesc.getText().toString();


        @Override
        protected void onPreExecute() {
            pbbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r) {
            pbbar.setVisibility(View.GONE);
            Toast.makeText(AddProducts.this, r, Toast.LENGTH_SHORT).show();
            if(isSuccess==true) {
                FillList fillList = new FillList();
                fillList.execute("");
            }

        }

        @Override
        protected String doInBackground(String... params) {
            if (proname.trim().equals("") || prodesc.trim().equals(""))
                z = "Please enter User Id and Password";
            else {
                try {
                    Connection con = connectionClass.CONN();
                    if (con == null) {
                        z = "Error in connection with SQL server";
                    } else {

                        String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH)
                                .format(Calendar.getInstance().getTime());

                        String query = "Update Producttbl set ProName='"+proname+"',ProDesc='"+prodesc+"' , OnDate='"+dates+"' where Id="+proid;
                        PreparedStatement preparedStatement = con.prepareStatement(query);
                        preparedStatement.executeUpdate();
                        z = "Updated Successfully";

                        isSuccess = true;
                    }
                } catch (Exception ex) {
                    isSuccess = false;
                    z = "Exceptions";
                }
            }
            return z;
        }
    }

AsyncTask task 4 – DeletePro(to delete product in our database):


public class DeletePro extends AsyncTask<String, String, String> {



        String z = "";
        Boolean isSuccess = false;


        String proname = edtproname.getText().toString();
        String prodesc = edtprodesc.getText().toString();


        @Override
        protected void onPreExecute() {
            pbbar.setVisibility(View.VISIBLE);
        }

        @Override
        protected void onPostExecute(String r) {
            pbbar.setVisibility(View.GONE);
            Toast.makeText(AddProducts.this, r, Toast.LENGTH_SHORT).show();
            if(isSuccess==true) {
                FillList fillList = new FillList();
                fillList.execute("");
            }

        }

        @Override
        protected String doInBackground(String... params) {
            if (proname.trim().equals("") || prodesc.trim().equals(""))
                z = "Please enter User Id and Password";
            else {
                try {
                    Connection con = connectionClass.CONN();
                    if (con == null) {
                        z = "Error in connection with SQL server";
                    } else {

                        String dates = new SimpleDateFormat("MM/dd/yyyy", Locale.ENGLISH)
                                .format(Calendar.getInstance().getTime());

                        String query = "delete from Producttbl where Id="+proid;
                        PreparedStatement preparedStatement = con.prepareStatement(query);
                        preparedStatement.executeUpdate();
                        z = "Deleted Successfully";
                        isSuccess = true;
                    }
                } catch (Exception ex) {
                    isSuccess = false;
                    z = "Exceptions";
                }
            }
            return z;
        }
    }

Do you have any questions or queries on this post…please comment below and let me know what you think about this code.

More on Android and MS SQL :

Filling data in Android Spinner using MS SQL Database.

Using Stored Procedure in Android from MS SQL Server


Filling data in 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

 

download btn


  • Pingback: Connect Android to MS SQL Database. - ParallelCodes()

  • Pingback: Android Listview from MS SQL server • ParallelCodes()

  • nice article. Anywhere i need to modify the ConnectionURL with a port in order to connect to my server.

  • William Cook

    What if I don’t have IP address I just have the server name like s10.winhost.com

  • William Cook

    I have set a database on a web hosting site and here is the connection string they have me I want to know how can I make your code work
    “Data Source=tcp:s10.winhost.com;Initial Catalog=DB_xxxxx_testdb;User ID=DB_xxxxx_testdb_user;Password=******;Integrated Security=False;”

  • It will work only put your data source name instead of ip address. I’m using it for my client application to connect to their database in my application like below in connectionclass :
    ip = “tcp:s10.winhost.com”;
    classs = “net.sourceforge.jtds.jdbc.Driver”;
    db = “database name”;
    un = “your username”;
    password = “your password;

  • Fariba

    Thanks for Clear, Applicable and Usefull Tutorial.

  • Nidhin Kumar

    Nice Tutorial,but can u say how to upload an image from android to ms sql database pls.

    • Hi Nidhin, I am trying to do so, will post it within two or three days

  • Christian

    Good day! I am new in android studio. I’ve been connecting android studio and MSSQL SERVER 2000 for a couple of weeks but it keeps on showing me a message “Unfortunately has stop”.
    Thanks

    • Have you added the Jar Library and followed all steps properly. Also What error you are getting it while running the Application in the Logcat output??

      • Christian

        Yes I added the jar file in Libraries or Should I put it in libs? LogCat error No file directory.

    • siva kumar

      I tried with ms sql server local host, in emulator blank screen and errors shown, pls help me, how to connect to ms sql server 2012.

      • Hi Siva. What error you are getting..please check logcat output.
        It might me NullPointerException I guess….

        • siva kumar

          thxs no error its blank screen. pls view following to connect ms sql server. and I am completely confused with which method to be used to connect ms sql database. pls help me out.
          ***********************************************
          protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
          System.out.print(“aaa”);
          Log.i(“Android”,” MySQL Connect Example.”);
          Connection conn = null;
          try {

          String driver = “net.sourceforge.jtds.jdbc.Driver”;

          Class.forName(driver).newInstance();

          //test = com.microsoft.sqlserver.jdbc.SQLServerDriver.class;

          String connString = “jdbc:jtds:sqlserver://home:1433;databaseName=opt;user=sa;password=sa123; integratedSecurity=true;”;

          String username = “sa”;

          String password = “sa123”;

          conn = DriverManager.getConnection(connString,username,password);

          Log.w(“Connection”,”open”);

          Statement stmt = conn.createStatement();

          ResultSet reset = stmt.executeQuery(“select * from dept”);
          //Print the data to the console

          while(reset.next()){

          Log.w(“Data:”,reset.getString(3));

          Log.w(“Data”,reset.getString(2));

          }
          conn.close();
          } catch (Exception e)

          {

          Log.w(“Error connection”,”” + e.getMessage());

          }
          }

          • siva please use IP address of your local PC on which you have installed SQL or server name on which your database in present.

  • Thalesh Soni

    Same your code not run show error Unfortunately , MySQLApp has stopped

    • Please say what logcat output you are getting? Also you are using Eclipse ADT or Android Studio.

  • Thalesh Soni

    Android Studio.

  • Thalesh Soni

    and logcat

    08-27 07:04:06.638 13323-13323/? D/dalvikvm﹕ Not late-enabling CheckJNI (already on)

    08-27 07:04:06.898 13323-13323/app.mysqlapp E/Trace﹕ error opening trace file: No such file or directory (2)

    08-27 07:04:07.217 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)

    08-27 07:04:07.217 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested

    08-27 07:04:07.217 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve interface method 14038: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z

    08-27 07:04:07.217 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002

    08-27 07:04:07.228 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode

    08-27 07:04:07.228 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve interface method 14042: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;

    08-27 07:04:07.228 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x72 at 0x0002

    08-27 07:04:07.348 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations

    08-27 07:04:07.348 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve virtual method 401: Landroid/content/res/TypedArray;.getChangingConfigurations ()I

    08-27 07:04:07.348 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002

    08-27 07:04:07.348 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType

    08-27 07:04:07.348 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve virtual method 423: Landroid/content/res/TypedArray;.getType (I)I

    08-27 07:04:07.358 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002

    08-27 07:04:07.537 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawable, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawable

    08-27 07:04:07.537 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve virtual method 364: Landroid/content/res/Resources;.getDrawable (ILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;

    08-27 07:04:07.537 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002

    08-27 07:04:07.537 13323-13323/app.mysqlapp I/dalvikvm﹕ Could not find method android.content.res.Resources.getDrawableForDensity, referenced from method android.support.v7.internal.widget.ResourcesWrapper.getDrawableForDensity

    08-27 07:04:07.537 13323-13323/app.mysqlapp W/dalvikvm﹕ VFY: unable to resolve virtual method 366: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;

    08-27 07:04:07.537 13323-13323/app.mysqlapp D/dalvikvm﹕ VFY: replacing opcode 0x6e at 0x0002

    08-27 07:04:07.708 13323-13329/app.mysqlapp D/dalvikvm﹕ GC_CONCURRENT freed 198K, 9% free 2640K/2900K, paused 5ms+6ms, total 80ms

    08-27 07:04:07.828 13323-13329/app.mysqlapp D/dalvikvm﹕ GC_CONCURRENT freed 228K, 10% free 2885K/3204K, paused 5ms+4ms, total 40ms

    08-27 07:04:07.828 13323-13323/app.mysqlapp D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 22ms

    08-27 07:04:08.038 13323-13329/app.mysqlapp D/dalvikvm﹕ GC_CONCURRENT freed 294K, 11% free 3034K/3388K, paused 5ms+4ms, total 65ms

    08-27 07:04:08.318 13323-13323/app.mysqlapp E/ERRO﹕ Network error IOException: socket failed: EACCES (Permission denied)

    08-27 07:04:08.458 13323-13329/app.mysqlapp D/dalvikvm﹕ GC_CONCURRENT freed 249K, 9% free 3194K/3496K, paused 6ms+4ms, total 130ms

    08-27 07:04:08.608 13323-13323/app.mysqlapp D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so

    08-27 07:04:08.618 13323-13323/app.mysqlapp D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so

    08-27 07:04:08.627 13323-13323/app.mysqlapp D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so

    08-27 07:04:08.637 13323-13323/app.mysqlapp D/﹕ HostConnection::get() New Host Connection established 0x2a17e4c0, tid 13323

    08-27 07:04:08.707 13323-13323/app.mysqlapp W/EGL_emulation﹕ eglSurfaceAttrib not implemented

    08-27 07:04:08.727 13323-13323/app.mysqlapp D/OpenGLRenderer﹕ Enabling debug mode 0

    08-27 07:07:12.197 13323-13323/app.mysqlapp D/AndroidRuntime﹕ Shutting down VM

    08-27 07:07:12.197 13323-13323/app.mysqlapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a71930)

    08-27 07:07:12.217 13323-13323/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main

    java.lang.NullPointerException

    at app.mysqlapp.MainActivity$1.onClick(MainActivity.java:47)

    at android.view.View.performClick(View.java:4204)

    at android.view.View$PerformClick.run(View.java:17355)

    at android.os.Handler.handleCallback(Handler.java:725)

    at android.os.Handler.dispatchMessage(Handler.java:92)

    at android.os.Looper.loop(Looper.java:137)

    at android.app.ActivityThread.main(ActivityThread.java:5041)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

    at dalvik.system.NativeStart.main(Native Method)

    08-27 07:07:14.428 13323-13323/app.mysqlapp I/Process﹕ Sending signal. PID: 13323 SIG: 9

  • Thalesh Soni

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    add = (Button) findViewById(R.id.btnadd);
    errorlbl = (TextView) findViewById(R.id.lblerror);
    name = (EditText) findViewById(R.id.txtname);
    address = (EditText) findViewById(R.id.txtaddress);
    pincode = (EditText) findViewById(R.id.txtpincode);
    ipaddress = “10.130.7.165”;
    db = “Pay”;
    username = “sa”;
    password = “Cin@123”;
    connect = ConnectionHelper(username, password, db, ipaddress);
    add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    try {
    st = connect.createStatement();
    preparedStatement = connect
    .prepareStatement(“insert into studentRecord(Name,Address,Pincode) values (‘”
    + name.getText().toString()
    + “‘,'”
    + address.getText().toString()
    + “‘,'”
    + pincode.getText().toString() + “‘)”);
    preparedStatement.executeUpdate();
    errorlbl.setText(“Data Added successfully”);
    } catch (SQLException e) {
    errorlbl.setText(e.getMessage().toString());
    }
    }
    });
    }

  • Thalesh Soni

    Show 08-27 07:07:12.217 13323-13323/app.mysqlapp E/AndroidRuntime﹕ FATAL EXCEPTION: main

    java.lang.NullPointerException

    at app.mysqlapp.MainActivity$1.onClick(MainActivity.java:47)

    Please help regarding this

  • Thalesh Soni

    Kindly help regard to sdk targetting and how to set

  • Jonathan Justo

    I have included the .jar and changed password, username, etc to match my database. However, connection returns null. Can somebody help me please!

  • Kunal Deogade

    I followed your tuts, but my app is getting crash
    and i am not able to get connection.

  • Kunal Deogade

    I am using android sdk version 23.
    Also using jar jtds,
    but you didn`t mention about instance.

  • Kunal Deogade

    Why it is not working for kit kit version API level 19 to below.
    It works only for lolipop

    • It works it all version just see your target sdk version.

      • Kunal Deogade

        Ya i just changed my target sdk version from 23 to 19.
        But still it is not getting connected to SQL server

      • Kunal Deogade

        Here it is my Android Studio logcat

        10-06 12:07:42.475 21668-21668/com.example.aspl_test.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.aspl_test.test, PID: 21668
        java.lang.VerifyError: net/sourceforge/jtds/jdbc/TdsCore
        at net.sourceforge.jtds.jdbc.JtdsConnection.(JtdsConnection.java:359)
        at net.sourceforge.jtds.jdbc.Driver.connect(Driver.java:184)
        at java.sql.DriverManager.getConnection(DriverManager.java:179)
        at java.sql.DriverManager.getConnection(DriverManager.java:144)
        at com.example.aspl_test.test.connectionHandler.connectionHelper(connectionHandler.java:44)
        at com.example.aspl_test.test.FullscreenActivity.onCreate(FullscreenActivity.java:65)
        at android.app.Activity.performCreate(Activity.java:5248)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2164)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2249)
        at android.app.ActivityThread.access$800(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1212)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5052)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
        at dalvik.system.NativeStart.main(Native Method)

  • Pingback: How to fill data in Android Gridview using MS SQL Database • ParallelCodes()

  • Pingback: How to fill Data in Android Spinner using MS SQL Database • ParallelCodes()

  • Pingback: cn84rtxw4dcwn4xnc4rwif()

  • Simon Mwai

    am a newbie in android dev, ooohh how i wish i can be able to connect and have data on android. I will post screen shots of my challenges

  • Poovizhi Chelladurai

    Hi it ocur error as error in sql server connection. Pls help to connect with sql server

    • What logcat says?

      • Poovizhi Chelladurai

        Error in connection with SQL server

        • There will be some logcat output. Please post that

          • Poovizhi Chelladurai

            Network error
            IOException: socket failed: EACCES (Permission denied)

          • Have you configured your SQL Server to allow remote connection?
            Is your Username, Password correct?

          • Poovizhi Chelladurai

            S My username and password is correct.And I’m Using My system as both client and server.

          • Poovizhi Chelladurai

            It display Exception while execution. Pls help to solve this problem

          • Poovizhi Chelladurai

            After entering username and password it load Progress-bar for long time and it doesn’t response any information or error

  • Poovizhi Chelladurai

    Thanks your app has supported to store data to sql server. Now I have doubt in Getting data from SQL SERVER to sqlite

  • Saurabh Singh

    Hi Hitesh,
    Thank You for this wonderful tutorial. This tutorial has helped me in many ways.
    I had a question, Since I am new to Android Development, I wanted to know a way to include a logout option in the addProduct page in the settings. Could you please help me out and guide me how to add that functionality.
    Thanks in advance

    • Hi Saurabh and thank you for your response on this post. I appreciate it.
      For Logout functionality you can use sharedpreferences. You can store user’s ID in it making a variable.

      • Saurabh Singh

        Could you please show me how to do that? or give me a link, since I am very new, I have no idea.
        I am really sorry if I am asking for too much.
        Thank You

      • Saurabh Singh

        Thank you Hitesh for your prompt response.

        Since I am very new, I have no idea how to do that. Could you please show me how or could you please provide me a link so that I can follow it and achieve the Logout functionality in the menu.

        Sorry if I am asking too much, But I would really appreciate it if you could help me with this problem.

        Thank You.

  • shashi patil

    hitesh im unable to insert values into db…… no errors nothing… what ll be the problem????

  • Poovizhi Chelladurai

    hi , I have doubt while inserting record to sql server. How to avoid duplicates while inserting row using where condition.
    Example. Same name should not be insert into sql server

    • Use Sql Contraints

      • Poovizhi Chelladurai

        I have tried String query = “insert into newcustomerdata (company_name,stn,source,company_profile) values “+”(‘” + customer + “‘,'” + station + “‘,'” + source + “‘,'” + profile + “‘) SELECT company_name FROM newcustomerdata WHERE company_name!='” + customer + “‘ “;

        • Use these commands in sql studio:
          alter table nwcustomerdata
          add constraint UniqueCustName Unique(company_name)

          alter table Department
          add constraint UniqueDpt Unique(Department_name)

  • Fish Liu

    Hi, I have downloaded your source code, I want to connect MSSQL 2000, but it can’t login, it said Exception
    02-07 22:01:04.853 2148-2163/hitesh.sqlapp W/EGL_emulation: eglSurfaceAttrib not implemented
    02-07 22:01:04.853 2148-2163/hitesh.sqlapp W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad71e740, error=EGL_SUCCESS
    02-07 22:01:06.820 2148-2163/hitesh.sqlapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab78cdc0
    02-07 22:01:07.832 2148-2163/hitesh.sqlapp E/Surface: getSlotFromBufferLocked: unknown buffer: 0xab78c3b0

    I use MSSQL Console Lite APP that can connect MSSQL 2000 SERVER

  • manoj kumar

    Hi sir thanks for the tutorial, i am having one question that is we writing username and password in java class so is that hackable one?

    • Yeah its hackable

      • manoj kumar

        Is there any way to protect it if yes what is the procedure. ?

  • Kumar

    Hi Sir…
    how to connect 3 table using joins query

  • najib khanafer

    do you have a example on how to view employee profile in an activity edit boxes based on employee id using sql 2008 r2

  • Arun Madhav

    Hi,

    Successfully created the same with Add Update and Delete from SQL Server.. Thank you very much….

    Also, I have checked the spinner module with your code and works fine..

    Please shed some light on how to incorporate a spinner in this example without including the connection section.

    Thanks in advance

    • Hound Hunter

      Hiii there i’ve follow above post regarding SQL connection with Android. I followed everything and write the code as it like above just one change which is ip address. Rest of the code and db data is same like above but when i run it it says “Error in connection with SQL server”. Please help you out.

      • Arun Madhav

        are you able to ping the IP address of the system in which the MSSQLSERVER service running? Also add port 8443with the IP address, like, 192.168.1.3:8443.
        Also check is the MSSQLSERVER services are running including browser service

    • Prakash Jang

      hi Arun. Am getting connection Error using the same codes. Do you get similar issue?

  • Hi, Sir Successfully created the same with update and delete from the SQL server Thank you so much..

    • Hound Hunter

      Hiii there i’ve follow above post regarding SQL connection with Android. I followed everything and write the code as it like above just one change which is ip address. Rest of the code and db data is same like above but when i run it it says “Error in connection with SQL server”. Please help you out. Waiting for your reply and thanks in advance

      • you have to give the uername,password,dtabase name server ip address like below:
        connect = CONN(“username”, “password”, “database name”, “your server IP”);
        private Connection CONN(String _user, String _pass,String _DB, String _server)
        {
        StrictMode.ThreadPolicy policy= new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        Connection conn=null;
        String ConnURL=null;
        try
        {
        Class.forName(“net.sourceforge.jtds.jdbc.Driver” ).newInstance();
        ConnURL= “jdbc:jtds:sqlserver://” + _server + “;” + “databaseName=” + _DB + “;user=” + _user + “;password=” + _pass + “;”;
        conn=DriverManager.getConnection(ConnURL);
        Log.d(“connection”, “open”);
        }
        catch(SQLException se){
        Log.d(“ERROR1”, se.getMessage());}
        catch(ClassNotFoundException e){
        Log.d(“ERROR2”, e.getMessage());}
        catch(Exception e){
        Log.d(“ERROR3”, e.getMessage());}
        return conn;
        }
        if still not working then print Log and check which code is not working.

  • hello sir i want to load sql data in autocomplete text view for auto suggestion in android i have tried but it’s not successful can you halp me..?

    Thanks in Advance..

  • Tony

    4-26 07:53:04.852 24012-24012/hitesh.sqlapp V/Activity: onStart hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:04.862 24012-24012/hitesh.sqlapp V/Activity: onResume hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:04.932 24012-24012/hitesh.sqlapp I/ActivityManager: Timeline: Activity_idle id: android.os.BinderProxy@4197c208 time:19636382

    04-26 07:53:08.592 24012-24012/hitesh.sqlapp V/Activity: onPause hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:08.732 24012-24012/hitesh.sqlapp W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection

    04-26 07:53:09.002 24012-24012/hitesh.sqlapp V/Activity: onSaveInstanceState hitesh.sqlapp.MainActivity@419802a0: Bundle[{android:viewHierarchyState=Bundle[{android:views={16908290=android.view.AbsSavedState$1@4177b1d8, 2131361792=TextView.SavedState{41b0d140 start=9 end=9 text=201110467}, 2131361793=TextView.SavedState{41b0d260 start=9 end=9 text=rlagustjq}, 2131361794=android.view.AbsSavedState$1@4177b1d8, 2131361795=android.widget.ProgressBar$SavedState@41b0d380}, android:focusedViewId=2131361793}]}]

    04-26 07:53:09.002 24012-24012/hitesh.sqlapp V/Activity: onStop hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:09.012 24012-24012/hitesh.sqlapp V/Activity: onTrimMemory hitesh.sqlapp.MainActivity@419802a0: 20

    04-26 07:53:11.482 24012-24012/hitesh.sqlapp V/Activity: onStart hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:11.482 24012-24012/hitesh.sqlapp V/Activity: onResume hitesh.sqlapp.MainActivity@419802a0

    04-26 07:53:11.512 24012-24012/hitesh.sqlapp I/ActivityManager: Timeline: Activity_idle id: android.os.BinderProxy@4197c208 time:19642967

    04-26 07:53:32.952 24012-24025/hitesh.sqlapp E/ERRO: I/O Error: DB server closed connection.

    what’s mean? help me

  • Aakriti Mehrotra

    hi ,

    I am able to get the connection and query is being fired on my db, which I verified using profiler. But the problem is application is crashing on accessing Resultset .next(). Please let me know if there is something I am missing out.

    • Write SQLException in the try catch block.
      try{
      }catch(SQLException ex){
      String error = ex.getMessage().toString();

      }
      It’s coming because resultset might be empty.

  • Pingback: Android Import excel into Sqlite Database()

  • Sepaka Hlongwane

    Hi Hitesh,

    Thanks for your tutorial, it really works. However, I’m having a bit of a problem accessing the SQL server on android device, I get “Error in connection with SQL server”, BUT it works fine when opening the application on emulator.

    The IP address used is accessible on my device, I checked this by accessing a web site running on my machine using my device. My device and machine (the one hosting SQL server) are both on the same network. I tried both WIFI and LAN.

    Any ideas what to check here ?

  • Ang Kai

    Hi Sir,
    can i make the String ip = “”; as flexible?
    that’s means can i keyin in EditText, and get the ip from Edit Text.
    Pls help me, Thanks and Regard.

  • brasco18

    I don’t know if I set things up wrong, but in order to get the list to populate, I had to add the following code to ‘oncreate’ in the ‘addproducts’ class:

    FillList fillList = new FillList();
    fillList.execute(“”);

  • Prakash Jang

    Hi I used the codes below but getting error msg
    “E/ERRO: Network error IOException: Permission denied”
    Please help

    • ต้อง รัก

      check permission in Androidmanifests

      • Prakash Jang

        permission ok in manifest.

        any other suggestion please

        • ต้อง รัก

          can you show your logcat?

          • Prakash Jang

            Thanks for your help.

  • Erik Fok

    This shit is awesome, thanks!

  • Loren

    hi i want ask again.. I used the codes but in my application getting msg “Exceptions”
    please help me

  • Alayn A Arambula

    hello… where can I download the example complete source code? or can you please please send it to alayns@gmail.com… thanks in advance

  • Aashish Nikalaje

    hey when i do this it works only n local machine only but when i installed app on device it says server cannot found can you tell how i can do login and via device instead of local machine

    • ต้อง รัก

      can you show your logcat?