Thursday, July 12, 2012

Android MySQL Client (Part 2)

Insert data to a database.

My first tutorial Android MySQL client is about read data from a MySQL database. Here I'm going to insert data to MySQL database using an Android program. Concept is same as before (Before start test this read first tutorial.)

Program has three main parts.
1. Database (MySQL)
2. Java web service.
3. Android application.

Java web service deployed on Tomcat server has a method which accepts two values and it runs a quarry on database to insert data & also this method returns a string.
The Android application calls that web service method remotely with two values using ksoap library. Then web service runs a query on database table and inserts data

1. First create the database and table.


USE login;

name varchar(20),
password  varchar(20)

2. Then create the web service
Here is the content of my web service
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

public class Users {
 public String insertData(String userName,String userPassword){
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","chathura");
   PreparedStatement statement =  con.prepareStatement("INSERT INTO users(name,password) VALUES ('"+userName+"','"+userPassword+"');");
   int result = statement.executeUpdate();
   catch(Exception exc){

  return "Insertion successfull!!";

In line 12 root and chathura are user and the password. Change those with your username and the password.
This java web service has JDBC connector to access the database. Click here to download the connector.Import JDBC connector to your project. This tutorial is about importing the ksaop library. In the same way you can import JDBC library also. It is simple
You can implement the web service easily by following my these posts.
1. Create java web service in Eclipse using Axis2 (Part 01) 
2. Create java web service in Eclipse using Axis2 (Part 02) 

3. Android application.

The Android application uses ksoap2 library to access java web service. You can find More details about implementation of Android client applications from here. If you are planning to use new Android version read this tutorial.

Here is the code for Android application.
You need to change name space, url, soap action and method name according to your web service.

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidMySQLClientActivity extends Activity{
    private final String NAMESPACE = "";
    private final String URL = "";
    private final String SOAP_ACTION = "";
    private final String METHOD_NAME = "insertData";
    Button btninsert;
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
        btninsert = (Button)findViewById(;
        btninsert.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
    public void insertValues(){
     SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
     EditText userName = (EditText) findViewById(;
     String user_Name = userName.getText().toString();
     EditText userPassword = (EditText) findViewById(;
     String user_Password = userPassword.getText().toString();
     //Pass value for userName variable of the web service
        PropertyInfo unameProp =new PropertyInfo();
        unameProp.setName("userName");//Define the variable name in the web service method
        unameProp.setValue(user_Name);//Define value for fname variable
        unameProp.setType(String.class);//Define the type of the variable
        request.addProperty(unameProp);//Pass properties to the variable
      //Pass value for userPassword variable of the web service
        PropertyInfo passwordProp =new PropertyInfo();
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
        try{, envelope);
            SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
            TextView result = (TextView) findViewById(;
     catch(Exception e){


4.Code for main.xml file







5. Content of the Manifest.xml (Add internet permission)


Note : Click here to download the Android project.
Do you think this is helpful ? Please write your ideas :)


  1. hi Chathura can you post the code how to login so that after sucessfull login it open the only screen having that valid user detail only and he can perform insert ,delete and update operation.

  2. hello there and thank you for your information – I've definitely picked up something new from right here. I did however expertise a few technical points using this web site, since I experienced to reload the site lots of times previous to I could get it to load properly. I had been wondering if your web host is OK? Not that I am complaining, but slow loading instances times will very frequently affect your placement in google and could damage your high-quality score if advertising and marketing with Adwords. Well I am adding this RSS to my e-mail and could look out for much more of your respective intriguing content. Make sure you update this again soon.[url=]payday loans[/url]

    payday loans
    Here is my webpage payday loans

    1. Thanks for your comment.
      This is a blog created using blogger of Google. Normally blogger blogs take sometime to load and here I have used syntax highlighter to make codes more readable that is also increases loading time. I'm sorry for that

  3. This is my first time νisit at herе and i аm truly impressеd tο rеad evеrthing at one рlасe.
    Check out my web blog ; reklama internetowa

  4. You have given the class file of the tomcat server can u write the servlet for the same coding.

  5. I have learned a number of important things via your post.

    I might also like to convey that there may be a situation where you will have a loan
    and do not need a co-signer such as a Government Student Aid Loan.
    But if you are getting a borrowing arrangement through a standard lender then you need to be able to have a cosigner ready to allow you
    to. The lenders may base any decision over a few elements but the most important will be your
    credit history. There are some loan merchants that will furthermore look at your
    job history and choose based on this but in many cases it
    will hinge on your report.
    Feel free to visit my blog ... what is premature ejaculation

  6. I have been browsing online more than 3 hours today, yet I never
    found any interesting article like yours. It is pretty worth enough for me.
    Personally, if all webmasters and bloggers made good content as you did, the net will be a lot more useful than
    ever before.
    My website incontinence product

  7. hey bro , you should put your blog on top in Google search . I feel glad as i able to find your blog at-last.. Your blog is so informative and helpful... keep it man , and thanks for sharing..

  8. Hey bro , your blog is so helpful and informative. You should keep ur blog on top in Google search. I feel glad at-last i able to find ur blog . Thanks

  9. hii i have came across your blog its awsume!!!keep it up your good work.i have already working on posting images/videoes from android app to web any post about posting images/vidoes from android app to webservice

  10. Great Work!
    My method insertData is calling, but receiving null, null. In the android client the values is passed.

  11. Where i get the following NAMES...
    NAMESPACE = "http://localhost:8080/loginwebservice/";
    URL = "http://localhost:8080/loginwebservice/services/insertdata?wsdl";
    SOAP_ACTION = "http://localhost:8080/loginwebservice/insertdata";
    METHOD_NAME = "insertdata";

  12. hello first of all felizitarte for large work, I am Spanish and devido English my limited knowledge I have difficulty understanding (I'm rooting for the application of google) I read all your post and I am trying to do a project, I have all finished but when passing it to real mobile application closes, I'll leave my email if you want me to send the project and guide me a bit so thank you very much

  13. hello first of all felizitarte for large work, I am Spanish and devido English my limited knowledge I have difficulty understanding (I'm rooting for the application of google) I read all your post and I am trying to do a project, I have all finished but when passing it to real mobile application closes, I'll leave my email if you want me to send the project and guide me a bit so thank you very much

  14. Sir,
    My application is running on emulator but not in external device (mobile),My administrator has provided me one public ip.Tomcat server is running on localhost.public ip has been translated to my local from external device(mobile) browser wsdl file is opening(with public ip).But application is not running.Please help.

  15. bro can u show us a simple jdbc android which sends data to mysql and retrieve
    pls help me asap