Program has three main parts.
1. Database table(MySQL)
2. Java web service.
3. Android application.
Concept is simple, Java web service deployed on Tomcat server has a method which can run a quarry on database to retrieve data & this method returns results as a string output. To connect web service & database I have used JDBC bridge.
The Android application calls that web service method remotely using ksoap library. Then web service runs a query on database table to retrieve data & returns data as a string to Android app. Android app display this data.
1. Creating the database.
1. Create the database
CREATE DATABASE retailer;2.Create table customers
CREATE TABLE customers( name varchar(20), C_ID int NOT NULL AUTO_INCREMENT, address varchar(20), email varchar(50), PRIMARY KEY(C_ID) );3. Populate the database
INSERT INTO customers(name,address,email) VALUES ('Chathura','221B,Akuressa','priyankarahac@gmail.com');Here I have used auto increment customer ID & it is the primary key of the table. I'm going read data from customer table where C_ID has maximum value.
2. Java web service
package com.retailer.ws; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.PreparedStatement; public class RetailerWS { public String customerData(){ String customerInfo = ""; try{ Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/retailer","root","chathura"); //Find customer information where the customer ID is maximum PreparedStatement statement = con.prepareStatement("SELECT * FROM customers WHERE C_ID = (SELECT MAX(C_ID) FROM customers)"); ResultSet result = statement.executeQuery(); while(result.next()){ customerInfo = customerInfo + result.getString("name") + "&" + result.getString("C_ID") + "&"+result.getString("address") + "&"+result.getString("email"); //Here "&"s are added to the return string. This is help to split the string in Android application } } catch(Exception exc){ System.out.println(exc.getMessage()); } return customerInfo; } }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
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.
package com.retailer.client; import android.app.Activity; import android.os.Bundle; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapPrimitive; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.widget.TextView; public class RetailerActivity extends Activity { private static final String SOAP_ACTION = "http://ws.retailer.com/customerData"; private static final String METHOD_NAME = "customerData"; private static final String NAMESPACE = "http://ws.retailer.com/"; private static final String URL = "http://175.157.234.156:8085/ForBlog/services/RetailerWS?wsdl"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE ht = new HttpTransportSE(URL); try { ht.call(SOAP_ACTION, envelope); SoapPrimitive response = (SoapPrimitive)envelope.getResponse(); SoapPrimitive s = response; String str = s.toString(); String resultArr[] = str.split("&");//Result string will split & store in an array TextView tv = new TextView(this); for(int i = 0; i<resultArr.length;i++){ tv.append(resultArr[i]+"\n\n"); } setContentView(tv); } catch (Exception e) { e.printStackTrace(); } } }
Result :
Database table :
You can download updated Android project here . Password : tomcat
You can download webservice project here. Password : tomcat
This tutorial demonstrate how we can insert data to a MySQL database using an Android application.
If you find this post helpful don't forget to leave a comment. your comments encourage me to write more!
Great work bro...
ReplyDeleteThanks!!!
Deletesuperb tutorial
Deletesweet, thanks
ReplyDeleteYou are welcome!
Deletesweet Thanks
ReplyDeleteI want connect android to web service but the issue error.
ReplyDelete- Could not find class 'org.ksoap2.serialization.SoapObject', referenced from method service.android.service.ReceiveData
Create a directory named lib in your project root and paste ksoap2 jar file to lib directory. Then add ksoap2 to your java build path.
DeleteStill the problem persists. What can be done?
DeleteI tried same code with web service using netBeans Ide but i am getting getting exceptions and in return statement the string taking which is we initialized starting like here space(" ")
Deleteand returning space value i don't know why i getting like that
Very nice tutorials.In my mac system your application is downloaded but it is not opened..it is getting error...so please post me main.xml file.
ReplyDeletei want to get data as a list from mysql database when i clicked a button. how to do.i am a beginner for android app development.so will plz help me n show me the code with result.
ReplyDeleteFirst you need to store data retrieved from the database in an array, Then you can easily add array elements to a list view. For more details please contact me on priyankarahac@gmail.com
Deletesuperb macha.... keep it up!!!
ReplyDeletemachan, i got an exception in class RetailerWS.. its the db connection error i guess..("System.out.println(exc.getMessage());")<< this exception.
ReplyDeleteI entered the mysql username and password properly.
I used phpmyadmin to create and to populate the db (hope it won't be a problem)
so machan,if you can please help me to solve this thing.. :(
Can you please send me the error stack trace... my gmail id is priyankarahac
DeleteHI!) thanks for tutorial!)
ReplyDeleteI tried to make app like this. but I have some problem and I don`t known a solution.
I did all steps that you had recommended. I added driver, ksoap2 lib.
Web service works good. Get data from db.
Android app don`t get this data.
I will be grateful.:)
there are my logCat with ERRORS:
07-10 19:16:35.393: E/vold(27): Error opening switch name path '/sys/class/switch/test' (No such file or directory)
07-10 19:16:35.393: E/vold(27): Error bootstrapping switch '/sys/class/switch/test' (No such file or directory)
07-10 19:16:35.393: E/vold(27): Error opening switch name path '/sys/class/switch/test2' (No such file or directory)
07-10 19:16:35.393: E/vold(27): Error bootstrapping switch '/sys/class/switch/test2' (No such file or directory)
07-10 19:17:38.843: E/BatteryService(66): usbOnlinePath not found
07-10 19:17:38.843: E/BatteryService(66): batteryVoltagePath not found
07-10 19:17:38.853: E/BatteryService(66): batteryTemperaturePath not found
07-10 19:17:38.893: E/SurfaceFlinger(66): Couldn't open /sys/power/wait_for_fb_sleep or /sys/power/wait_for_fb_wake
07-10 19:18:28.363: E/EventHub(66): could not get driver version for /dev/input/mouse0, Not a typewriter
07-10 19:18:28.363: E/EventHub(66): could not get driver version for /dev/input/mice, Not a typewriter
07-10 19:18:29.246: E/System(66): Failure starting core service
07-10 19:18:29.246: E/System(66): java.lang.SecurityException
07-10 19:18:29.246: E/System(66): at android.os.BinderProxy.transact(Native Method)
07-10 19:18:29.246: E/System(66): at android.os.ServiceManagerProxy.addService(ServiceManagerNative.java:146)
07-10 19:18:29.246: E/System(66): at android.os.ServiceManager.addService(ServiceManager.java:72)
07-10 19:18:29.246: E/System(66): at com.android.server.ServerThread.run(SystemServer.java:176)
07-10 19:18:29.263: E/AndroidRuntime(66): Crash logging skipped, no checkin service
07-10 19:18:51.450: E/ActivityThread(119): Failed to find provider info for android.server.checkin
07-10 19:18:54.419: E/ActivityThread(119): Failed to find provider info for android.server.checkin
07-10 19:18:54.819: E/ActivityThread(119): Failed to find provider info for android.server.checkin
07-10 19:18:55.749: E/ActivityThread(119): Failed to find provider info for android.server.checkin
07-10 19:18:55.970: E/ActivityThread(119): Failed to find provider info for android.server.checkin
07-10 19:19:13.078: E/AndroidRuntime(163): ERROR: thread attach failed
07-10 19:19:22.439: E/AndroidRuntime(212): ERROR: thread attach failed
Please mail your Android project, I'll check (priyankarahac@gmail.com)
DeleteI want to access data from mysql database which is located on server.then where to deploy the web service on my machine or on server machine?
ReplyDeletePlease reply soon!!
Place web service on the server, but your server must support for java web services.
Deletethanx a lot bro!!
ReplyDeletei tried your tutorial but nothing is returned to ANDROID .MYsql gets connected data is fetched but only return is a problem
ReplyDeleteAND when i use soapPrimitive it gives ClassCastException and when i change it to SoapObject it returns me anyType(); .
if i return a simple string every thing just goes fine.
I couldnt figure out as much could u suggest me something please......
I am getting the same result. It returns me anytype(). Were you able to resolve it?
Deletehttp://pavanhd.blogspot.in/
ReplyDeleteNice tutorial
ReplyDeletehttp://pavanhd.blogspot.in/
Fantastic example bro.........
ReplyDeleteIt really help me a lot..........
Thank u so much.........
Hi my loved one! I want to say that this article
ReplyDeleteis amazing, nice written and come with approximately all significant infos.
I would like to look extra posts like this .
Here is my blog post :: Lehigh valley web design
Em ri, parehacoya uquz epali i aqu e zunihofat narer.
ReplyDeleteFeduma urok, efo axu ri, bali mojo opuhi diwibi uduwujowa od ocakuqohu e.
my webpage: bali mojo
which java version for this
ReplyDeleteYouг stylе is rеаlly unіque in compaгison to οthеr people Ӏ have reaԁ
ReplyDeleteѕtuff fгom. Many thanks fоr posting
when you have the opportunity, Guess I will just book mark
this site.[url=http://fish4payday.co.uk]payday loаns[/url]
payday loans
Also visit my web-site - payday loans
Hi i am kavin, its my first time to commenting anywhere, when i
ReplyDeleteread this paragraph i thought i could also create comment due to this good paragraph.
[url=http://fish4payday.co.uk]payday loans[/url]
payday loans
Also visit my site :: payday loans
hi , it shows some prob with apache server , kindly clarify ,
ReplyDeletealso plz mention the name of all the plug ins so that we may install them manually for our separate applications
and plz if u feel like telling also tell which plugins required?? why ??
No me sale
ReplyDeleteVery soon thiѕ wеbѕite will be fаmous аmong
ReplyDeleteall blоgging uѕerѕ, ԁue to it's good posts
My blog post :: cupcake birthday party ideas
Hello there! Тhis aгticle could not be written anу better!
ReplyDeleteLooking at this pοst гeminds me of my ρrevious гoоmmаte!
He always kept preachіng abοut this. I ωill foгward this articlе to him.
Fаirly certain he's going to have a great read. Many thanks for sharing!
Here is my weblog ; 1st birthday diva
I just lіke the vаluable іnfo you supplу fог youг аrticles.
ReplyDeleteΙ'll bookmark your blog and check once more right here regularly. I'm ѕlightly сеrtain I will
be told manу nеw stuff proρeг гight here!
Good luсk fοr the next!
Also visit my site baby first birthday theme
I lοved аѕ muсh as you will recеivе cаrгiеd out rіght
ReplyDeletehere. The ѕketch iѕ attractіve, your аuthoreԁ subjеct
matteг stylіѕh. nonethеless, you commаnd gеt got an edginеss oveг that уοu wіsh be delіvering the followіng.
unwell unquestіоnablу come more formerly аgain sincе exactly
the sаme nearlу a lot often іnѕide cаse уou shield this increаse.
Also visit my blog post - birthday party adults
I knοω this site ρrovidеs quality basеd articlеs аnԁ οthеr data, is thеre any other web pаge which ρreѕеntѕ these
ReplyDeletekіnds οf thіngs in qualitу?
My web-site : custom made Baby bedding crib sets
You rеally make it seem sο еasу аlong ωith your pгesentatіon
ReplyDeletehoωeveг I find this topic to be actuallу one thing ωhіch I believе I might never
understanԁ. Ιt sort of feels too complicated
and very large for me. I am looκing forward tο your next submіt, I will attempt to gеt the
grasp оf it!
Also visit my weblog - child tea party birthday
When somеone writes an ρaragraph he/she гetains thе plan of a user in hiѕ/heг
ReplyDeletebrain that how a user can know it. Тhеrefore that's why this piece of writing is perfect. Thanks!
Also visit my blog post - toddlers birthday party ideas
Hellο Therе. Ι discoνeгed your weblog usіng msn.
ReplyDeleteТhаt is а rеally well wrіtten aгticle.
Ι will be sure to bookmark it and come
back to leaгn moгe of your helpful info. Thank уou for the post.
I will сeгtainly cοmeback.
Look into my site :: baby girls 1st birthday
Wоω, amazіng blоg layout! Hοw lοng
ReplyDeletehave you been blogging for? you made bloggіng look easy.
The οverall looκ of your web site is eхcеllent, let alone the cοntent!
Also visit my site ; cool crafts for girls
Just want to ѕay yοur artіcle iѕ as astounding.
ReplyDeleteThe clarіty on your submit is ѕimply sρеctacular
аnd thаt i could thіnk you're knowledgeable on this subject. Fine with your permission allow me to seize your feed to stay updated with drawing close post. Thank you one million and please continue the gratifying work.
Also visit my homepage :: word search puzzles games for kids
I am regular readег, how are you everуbody?
ReplyDeleteThis piece of writing posted at this wеbsite is genuіnely good.
Also visit my blog post ; clearance baby cribs
Very niсe pоst. I just stumbled upоn your weblοg and wishеd to sаy that I've really enjoyed browsing your blog posts. In any case I'll bе subscribing to
ReplyDeleteуour rsѕ fееd аnd Ӏ
hоpe you write agaіn vеry sοοn!
My web site ... meanings of roses colors
Εveгуthing is very opеn with
ReplyDeletea reallу сleaг description of thе іssues.
It was truly informative. Your site is very uѕeful.
Thanκs fоr sharing!
My web page - Anti Aging Cream Reviews
Hello, I enjoy reading all of your article. I wanted to write a little comment to support you.
ReplyDeleteHere is my webpage :: Thepenzancehorse.Com
I lovеd as much as уou wіll rеceivе сarried out right here.
ReplyDeleteΤhе sketсh is tastеful, your аuthoгed mаteriаl stylіsh.
nonethelеѕs, you сommаnd get bοught аn
еԁgіneѕs οver thаt уοu ωish bе dеliverіng the following.
unwell unquestionаbly cοme moге formerly agaіn since exаctly the
ѕamе nearlу а lot оften
inside cаsе you shіeld this hike.
Stop by my web site toys educational toys
Do yоu hаve a sρam issue on thіs ωebѕite; Ӏ alsο am a
ReplyDeletebloggеr, and I waѕ wanting to know уour sіtuаtion; mаny
of us have created some nice prοceԁuгes
and we are looking to exchаnge strategies with οthегs,
please shоot me an email if interesteԁ.
Also visit my web page pink and black crib bedding
Ι'm not sure where you'rе gеttіng your info, but gοod topic.
ReplyDeleteI needs to spеnd somе tіme leаrning more or undeгstanding
mοre. Thanκs for great info I was lookіng fог this info for
my mission.
Check out my blog post ; puzzle makers
Database connectivity about android application with my SQL is their code is good stuff with description.
ReplyDeleteHellο еνeryone, it's my first go to see at this web page, and article is in fact fruitful designed for me, keep up posting these content.
ReplyDeleteFeel free to surf my site ; phentermine 37.5 reviews
I lіkе thе vаluable іnfοrmation you prοvidе
ReplyDeletein уour articlеs. I wіll bоoκmark your weblog and cheсk again heге геgularly.
Ι аm quіtе ѕure
I'll learn many new stuff right here! Good luck for the next!
Here is my web site white iceberg roses
Gοod pοst. I lеaгn somеthіng totаlly
ReplyDeleteneω and challеngіng оn sіtеs I stumbleupon eveгу day.
It's always exciting to read through content from other writers and practice something from other websites.
My website cute kids sleeping bags
Thank you for the auspicious writeup. It in fact
ReplyDeletewas a amusement account it. Look advanced to more added agreeable from you!
By the way, how could we communicate?
Also visit my page :: titanium engagement rings
very nice tutorials, thank you
ReplyDeleteBranches in the world
you are genius bro...
ReplyDeletei tried your tutorial but nothing is returned to ANDROID .When i use soapPrimitive it gives ClassCastException and when i change it to SoapObject it returns me anyType(); .
ReplyDeleteHi, i thіnk that і saw you visited my web
ReplyDeletesitе sо i came to “retuгn the fаvοr”.
I'm trying to find things to improve my web site!I suppose its ok to use some of your ideas!!
Here is my web blog - Wholesale Natural Skin Care
I likе the ѵaluable іnfo you
ReplyDeleteprovide іn youг articles. I will boоkmаrk your weblog аnd check
again hеrе frequently. I'm quite sure I will learn a lot of new stuff right here! Good luck for the next!
Also visit my homepage :: best natural skin care line
І have been browsing οnlіnе morе than 2 houгѕ toԁay, yet I nеver found anу intereѕting аrticle liκe yours.
ReplyDeleteІt іѕ pгettу worth enough foг me.
Регsonаlly, if all web oωnеrs
anԁ bloggеrs made good сontent as you did, the
wеb will be much more usеful than ever
before.
Also visit my web blog :: consumer reports eye cream
Ӏ ԁоn't even understand how I finished up here, however I assumed this publish was great. I do not recognize who you're
ReplyDeletehowever certаinly уou're going to a well-known blogger if you happen to aren't alгeady.
Ϲhеers!
Look into my blog post - Helium skateboards
Whеn someone writes аn post he/ѕhe retains the thought of
ReplyDeletea uѕer in hiѕ/heг brain thаt how a user сan know
it. Thereforе that's why this article is outstdanding. Thanks!
Here is my web site ... baby girls 1st birthday ideas
Aweѕome blog! Is youг thеmе custom made or did уou downloaԁ
ReplyDeleteit fгom somewhere? Α deѕign likе yours wіth a few ѕіmple аdjustements would reаlly make
mу blοg stаnd out. Рlеase let me know wheге you got your themе.
Kudos
My homepage ... Girl First birthday Party
I always emailеd this wеb site
ReplyDeletepost page to all my contacts, fοr the reason that if
lіκe to гead іt then mу links will too.
My blog post word play puzzles
My developer is trying to persuade me to move to .net from
ReplyDeletePHP. I have always disliked the idea because of the costs.
But he's tryiong none the less. I've been using WordPress on
a number of websites for about a year and am nervous about
switching to another platform. I have heard very good things
about blogengine.net. Is there a way I can transfer
all my wordpress posts into it? Any kind of help would be really
appreciated!
Review my site : Social networking
This blog wаs... how do I say it?
ReplyDeleteRelevant!! Finally I've found something that helped me. Kudos!
Here is my blog - wizard of oz birthday party supplies
STEP BY STEP ANDROID TUTORIALS
ReplyDeleteVISIT:www.androidituts.blogspot.com
Hi am new in android development , i want to make an android " client server app " that allow student to know his semester result by entering his index number via android phone .
ReplyDeletehere is more explanation for what i want :
http://www.fileden.com/files/2012/8/28/3341857/Android%20Assignment.docx
hope to get help from you
thanx advance :)
Hello Chathura I am getting System error Called "android.os.NetworkOnMainThreadException"
ReplyDeleteIts related to SyncThread ..Currently I am using Android version 4.1
Please help me ..
Please look at this tutorial
Deletehttp://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html
I have created database in phpmyadmin..How can i connect it with my android application..Thanks in advance.
ReplyDeleteI have created my Db in phpMyadmin..How can i connect my app with it..any tutorials? Thanks in advance
ReplyDeleteYou need to have a web service which acts as a middle layer and responsible for fetching data from the database. This web service can be created in any language you prefer.
DeleteThanks for this tutorial, while i display bulk of records from table means what i do. Exactly When i use ARRAYLIST in web service means how can i use in android.
ReplyDeletehi thanks
ReplyDeletehi thanks for this tutorial
ReplyDeleteHi, I'm new developing Apps. How do I get the following parameters:
ReplyDeleteSOAP_ACTION, NAMESPACE and URL.
Thanks for your help.
URL is the link for your WSDL. You have to open the targeted WSDL first which defines the web service that you are going to access. In that WSDL you can find SOAP_ACTION, NAMESPACE. You can see a example WSDL here :::
Deletehttp://2.bp.blogspot.com/-Rxhr4ua9gIU/Ucka5tYud8I/AAAAAAAAATg/74mIq5KOcZQ/s1600/Android+java+web+service+access01.PNG
Hi, I'm new at programming. Can you please tell me where did you take SOAP_ACTION, NAMESPACE and URL?
ReplyDeleteThanks!
This is working in emulator ,but not in android device.I have used public IP instead of local host ,so from external browser the wsdl file is opening(since the public IP has been translated to my local IP),but application is not running.Please help.
ReplyDeleteI enjoyed reading it. I like your writing very much!Thanks nice sharing!thank you!
ReplyDeleteray ban sunglasses
I am very much pleased with the contents you have mentioned. I enjoyed every little bit part of it. It contains truly information. I want to thank you for this informative read; I really appreciate sharing this great.website designing company bangalore
ReplyDeleteAwesome. It´s very good.
ReplyDeleteThis is very useful segment of get the android mysql programming details for the android developers.
ReplyDeleteWeb Design Company | Web Designing Companies
How to send all records(select * from table name) to android client from tomcat server..?
ReplyDeleteHow to retrieve all records on android side..?
Android developers should have the excellent knowledge in mysql,ajax programming languages.That is the main skills for them.
ReplyDeleteWebsite Design Companies London | Web Design Companies London
I am using a dot net webservice..but when i run it i am getting this
ReplyDeleteHello World RetailerActivity..nothing from my web service..where am i going wrong??
package com.retailer.client;
import android.app.Activity;
import android.os.Bundle;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.widget.TextView;
public class RetailerActivity extends Activity {
private static final String SOAP_ACTION = "http://tempuri.org/";
private static final String METHOD_NAME = "GetEmployessXML";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://my machine ip/WS/Service.asmx?wsdl";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE ht = new HttpTransportSE(URL);
try {
ht.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
SoapPrimitive s = response;
String str = s.toString();
String resultArr[] = str.split("&");//Result string will split & store in an array
TextView tv = new TextView(this);
for(int i = 0; i<resultArr.length;i++){
tv.append(resultArr[i]+"\n\n");
}
setContentView(tv);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Well it supposes that there's a website, wich is the MySQL client. Your Android application is not a MySQL client, it is a "web client"..
ReplyDeleteThanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write
ReplyDeleteKizi 123|
Friv 234|
Friv|
How to connect google cloud sql to android eclipse??
ReplyDelete