I was working of an android project recently and now I guess .. I am done with my part. Yeah its a team of 4 and the project was divided accordingly. One of the responsibilities I was assigned was the development of Online Leader Board. While I was working, I searched through Internet and found a few examples as well, – I wonder which question Google couldn’t answer?
All of them were either to much complicatedly explained or didn’t cover the complete concepts behind a complete Client Server Communication In Android. Either the writers were assuming that the person who’ll land of this page will be intelligent enough to guess the other part or were simple not interested of posting a complete solution to someone’s problem. And for the same reason I am writing this post, so if someone else lands on this page while searching the same problem he/she could find a complete solution to their needs.
In this tutorial I’ll be assuming that you at least:
- Have a basic knowledge of android
- Have already developed a few small android application (e.g calculators, alarm, reminder etc.)
If you are new to android development, please leave me a comment and I might start from the beginning.
The Real Post Starts From Here:
In spite of using the 3rd party API’s, json classes etc. I’ll be using the default HttpClient from org.apache.http package. For those who want to get the code snippet just and not want me to explain it, the code will be as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet("http://example.com/script.php?var1=androidprogramming"); try { HttpResponse response = httpclient.execute(httpget); if(response != null) { String line = ""; InputStream inputstream = response.getEntity().getContent(); line = convertStreamToString(inputstream); Toast.makeText(this, line, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "Unable to complete your request", Toast.LENGTH_LONG).show(); } } catch (ClientProtocolException e) { Toast.makeText(this, "Caught ClientProtocolException", Toast.LENGTH_SHORT).show(); } catch (IOException e) { Toast.makeText(this, "Caught IOException", Toast.LENGTH_SHORT).show(); } catch (Exception e) { Toast.makeText(this, "Caught Exception", Toast.LENGTH_SHORT).show(); } |
- GET is used to know how actually the code is working.
- Default strings from android strings.xml are not used to avoid useless explanation for this tutorial but they are the recommended way too use while designing an app rather then hard coded strings.
Client server communication is this much simple when it comes to android.
- Create HttpClient with the default constructor.
- Create a HttpGet or HttpPost object depending upon your needs, in this case I made a GET object so that we can know whats going on.
- Initialize the object with a GET or POST url.
- Execute the GET/POST object through the Http and you’ll get the server’s response in the response object of HttpResponse.
Fetching Data From HttpResponse:
Now the next part is how to fetch data received from the server in HttpResponse object. The server response can be type casted into InputStream object which will then parse the response into simple String. here is the code to do that:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
private String convertStreamToString(InputStream is) { String line = ""; StringBuilder total = new StringBuilder(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); try { while ((line = rd.readLine()) != null) { total.append(line); } } catch (Exception e) { Toast.makeText(this, "Stream Exception", Toast.LENGTH_SHORT).show(); } return total.toString(); } |
So now the code is completed for the client side and we will be focusing on the server side script. The example above will show a notification of the string response the server will send back, here is the code snippet I wrote in php for the server side.
|
1 2 3 4 5 6 7 8 9 10 |
$connection = mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die('Unable to connect'); $db = mysql_selectdb(DB_NAME,$connection) or die('Database not found'); if(isset($_GET['var'])) : $query = "SELECT [a few parameters] FROM [some table] WHERE [some conditions]"; $resultset = mysql_query($query); $row = mysql_fetch_array($resultset) echo $row['[column name]']; else: echo "No get Request Received"; endif; |
Warning:
- Implement proper checks for data filtration. The code above was meant for the tutorial and is not enough to use in a market application.
This completes this small tutorial here, now a few of the most asked questions while doing the client server communication:
- Why not use the XML approach while performing the client server data transfer operations:
This was my first android application which used internet permissions and fetched data on runtime from server, I found it more interesting to work first manually with writing my own script and then go for the proper XML approach. - Why not use the JSON library for client server application in fact of using an array for GET or POST request:
Answer remains the same for this question as well. I have implemented my own methods and know how HTTP works in android. Next I’ll be using JSON and then switch to XML, JSON tutorial will be the next one in this series. - Some other questions:
Post them into the comments section and I’ll be happy to answer them right away. If you are enough experienced and found this approach not practicable while developing apps for the market, please provide your valuable feedback in that case as well. We warmly welcome a healthy and fruitful discussion here.
Internet Permissions
To get access to internet at Android, following field must be included to AndroidManifest.xml file of the project:
|
1 |
<uses-permission android:name="android.permission.INTERNET"></uses-permission> |
hi im totally new to this client server communication. i would like you to help me if possible i have to make an application in which user name and password have to get authenticated and will return to the user the database would be on the server itself..
Hi Devika, Sure, the application will work on the same principle this tutorial do. Try on your own and if you get any error or exception share it here and I’ll certainly help you out
can u share some more example codes to run on client server architecture …so that i can gain some confidence
I am already planing on some basic android tutorials, I’ll go through this once again or at least provide you with some of the samples soon.
how to extract(filter) data form web and access that data to my application
You’ll get the data echo’ed or printed by your php script in HttpResponse variable which then can be converted into a Java String as mentioned above to use in your programming logic. A point to be noted is that we receive a buffered stream in HttpResponse, so if you can manage to get along with it then there isn’t any benefit of converting the stream into String first. Hope I have made you clear, if you have any more doubts post them here and I’ll answer them as quickly as I can.
My application is like, extracting particular data(Events) form website, filter important information. eg. filter only sports events with time,date etc. from particular website. how can i do that?
I suppose the data (Events) you’ll be extracting from the web server is kept in a professional manner with time, date and its category stamped. For this example assume we have a table with (Please bother me with database not being normalized to level 3, its just an example
): 1. Event name 2. Event type 3. Time 4. Date We can simply call our script with an appropriate sql command to get us events related to sports category via passing some values like: example.com/event-filtering-script.php?eventtype=sports&date=02022012 The script will fetch the data out of these variables and ran a SQL query similar to: SELECT * FROM WHERE event_type=’sports’ AND date > ’23/12/2011′ and then will print the data which will then return to your response variable. P.S: The query might won’t work for the time and date but its just not at the top of my head. I’ll read it from the mySQL reference manual and post it here if get time, but its not a promise.
Great work Osama Keep it up
Thanks
hi dear shabrej ! ur tute is too much awesome. Dear would u like to tell me how the vidoe fetch from server side? i am working on E-Learning Project from where i’ve to fetch image/audio/video through json. Thank You!
The procedure would be the same as in this case but you have to encode the to bytestreams to make the multimedia attachments works, that what I can guess for now as I haven’t tried it myself, but I will once getting done with my exams and report back. Thanks for te appreciation though.
can u sent me the full code
My bad, I am busy with my university exams and am too late to respond, still I’ll try to find the project folder and will upload it for you. Stay tuned!
Osama Shabrez::: i followed the same thing as u said i created database in mysql ,wrote the php code and android code.now my doubt is i hosted php file in IIS(Internet Information Service Manager)(http;//10.0.0.108//myfile.php).But its not retrieving any thing from database,I struct here plzzzz i need ur help immediately .i need to submit my proj.with in weeks of time.every thing was done except this.if u could help me getting out of this i can doo remaining whole part
Hi, I am currently on the go and also busy with my university exams but would you mind sharing your code or stack trace if there is an error?
hey,i am able to retrieve data from database .but failed in converting to JSON object.the screen shot the error which i am getting is facebook.com/#!/groups/212713538768918/ urgently needed your help here is my java code::
and PHP file code: —Regards, R.Siva prasad (7702616462)
Hello everyone, please tell how can i access database of wordpress through android application please share any code example if any body have …
A tutorial on this topic is in process
No matter what i do it throws an exception. Using ICS. Please help. Thanks
I’ll look into it and will update the code as required. Appreciate that you reported.
hey,i got the solution for hoe to retrieve.but struggling with “how to send data from android to php file.needed ur helppp urgent….. the error i am getting is ” Notice: Undefined index: NAME in C:\xampp\htdocs\online\sample.php on line 1″ my java code is::
php file code is: can u plzz help me getting out of this. eagerly looking forward for ur response
php code is :
php code is: “” “”
hey hello, i am making a project for my submission in android and i phone a instant messenger and i want to user xmpp ,can u help me please..
Hi I regret getting back to you this much late, I was for hiking and still not at my home, but if you are still available I do have my mobile and laptop with my now, we can work it out.
hey, i sent you the link of my code in facebook message.plzz check it out
Salam Osama Shabrez hope you are fine and fit kindly send me this code i am getting error in above example i have university project of Remote Desktop Client kindly help me send me mail if possible plz.i am very thankful to you..
I’ll be uploading this project on GitHub today, you’ll be able to fork it from there then.
Hi, I am new to the Android, please can you temme in Android so how should i create http connection based on any simple program ? And can i know what are the basics should i know it for http connection?
Mind reading the above tutorial?
Your answer is already in there
hi i want to make a simple application on android.data transfer between to android mobile using internet…if any buddy having idea or code plzzz share with me… urgent!!!!!!!!!!!!!!!!!
In what prescriptive you are mentioning the android.data part here? to share the data among two phones with the same application or to transfer android.data of applications between two phones?
It is possible to send the data to server directly without using any php type of language…please replay fast..!!1
You can use any other web programming language you are easy with from whom you can get the
Request (GET/POST)variables data.hi, bro awesome Tut, can u please tell how can server communicate with android app in Asynchronous manner. server send command to android and in return android return data to server Thanx for u precious time Regards
Already working on, will update the post soon.
hey…is there any way we could create a client/server app… wherein using the gps, clients transmit their location to server..??
Hi Sumeet, Well GPS alone can not do this job, although you can get location using GPS and then transfer the coordinates to the app server for further processing. Of course you’ll have to add location based services permission in your application.
Salam Osama Shabrez hope u r fine…. i m beginner in android and getting an exception while running d above code .. could u plz suggest m d solution . with regards syed
StrackTrace or exact exception will be of lot more worth if you can provide.
Jazak Allah Khair (THANK YOU)
Hello!! I am working on a web server based project in android and I want to store images on server and process i.e to match that image with reference image which include matlab processing.Also,I am new for working on web server and web services but comfortable with android.So,please guide me what should I do for storing images on server and processing??
hello. I m creating the android application as “android wireless USB Storage device through USB/IP connection”. But I m comptitely new for that concept. Will u please tell me about some codes for that concept. Please Help me
Hiii…i am developing an app which will show the entertainment events held in the city, for which i have to extract data from websites… Can you please guide me as to how i can save the fetched web data into my SQLitedatabase…so that everytime i run my app, the data gets updated… Awaiting reply… Please reply soon
Have a Good Day!!!
hai, thanks for this valuable tutorial, it helped me a lot, i was in a confusion in doing this for a long time and after reading your tutorial it is over now. Thank you so much Now I have a little doublt.,.. you have used php in the serverside here.. My question is I dont want to use php, instead i want to use a java class for communicating with the database. so how will I do this? I i use a java file in the server then how will my code changes? Inside the HttpPost method, how should I write my url? I expect a quick reply, thanks in advance..
Phewww… thats useful! i thought i had to work through all over the internet to get the answers… really helpful for my ISD project! Love you man