Monday, July 9, 2012

Android php web service client

In this post I'm going to show you how we can access a very simple php web service from an Android application.
You can host your web service on wamp server installed in your machine or you can simply use a cloud server like 000webhost.

1. To keep things simple I'm going to use a dummy php code as follows
    <?php
        echo "Hello world!!!!"
  ?>
Create this php file and copy it in to www directory of wamp server or upload it in to a cloud server.

2. Here is the code for Android activity
import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

public class AndroidWebActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
        try {
           HttpResponse response = httpclient.execute(httppost);
           final String str =  EntityUtils.toString(response.getEntity());
           TextView tv = (TextView) findViewById(R.id.textView1);
           tv.setText(str);
        } 
       catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
        }
    }
}

Note : If you are using wamp server don't use local host for the url in line 18, use 10.0.2.2.
           Eg: http://10.0.2.2/android_connect/first.php
Don't forget to add internet permission.
Output of the program :

30 comments:

  1. Thank you so much Chatura for posting this :)

    ReplyDelete
  2. i am using wamp server and give ip 10.0.2.2:9999 still getting connection refused error...

    ReplyDelete
  3. Great blog here! Also your site loads up fast!
    What host are you using? Can I get your affiliate link to your host?

    I wish my site loaded up as quickly as yours lol
    Also see my web site > Madison

    ReplyDelete
  4. Oferim solutii software pentru industria Horeca.
    Soft pentru Restaurant,Bar,Fast food,Club.
    AB Soft Timsoara, HORECA MANAGER este o solutie software care permite urmarirea, controlul si
    reglarea activitatilor din firma dumneavoastra prin controlarea
    de la vanzare la materii prime in timp real.

    Softul a fost dezvoltat pentru a veni in intampinarea nevoilor aparute in desfasurarea activitatii intr-o locatie HORECA, astfel prin utilizarea monitorului cu TOUCH SCREEN de catre
    angajati, dumneavoastra aveti un control total asupra afacerii prin:

    -Scazamantul din stoc dupa retete sau unitar se face in momentul INCASARII MESEI !


    -Calculul in timp real al stocurilor de marfa (cantitativ si valoric)

    - Controlul vanzarilor pe ospatar in timp real (cantitativ si valoric)

    - Controlul vanzarilor totale in timp real (cantitativ si valoric)

    - Rapoarte cantitativ – valorice – procentuale pe grupele de produse
    si pe fiecare produs in parte.

    - Listare NIR la pret de achizitie sau de vanzare.


    - Fisa Magazie pe produs pe perioada.

    - Grafice vanzari pe orele zilei sau pe zilele saptamanii Sistemul software
    va mai ofera urmatoarele avantaje:

    Reducerea erorii umane in calculul notelor de plata si a stocurilor.


    Eliberarea automata a bonurilor fiscale (pt DATEX MP55 sau compatibile
    cu PC)

    Siguranta datelor – HORECA MANAGER ofera siguranta datelor in sistem cu nivele de acces distincte
    pentru angajat si pt Administrator.

    Promptitudine si reactie rapida la comenzile utilizatorilor.


    Se pot utiliza un numar nelimitat de produse grupate in categorii.


    Interfata foarte prietenoasa, customizabila pt fiecare client.


    Reducerea costurilor prin o corecta gestionare
    a materiilor prime, avand la dispozitie rapoartele de consum pentru a putea alcatui o comanda de
    aprovizionare.

    Controlul angajatilor prin informatiile oferite de catre
    BORDEROUL DE INCASARI OSPATAR: Data si ora intrarii in tura precum si
    a iesirii,Numarul de comenzi servite,Valoare vanzari desfasurata
    pe categoriile de plata (Numerar,Card,Protocol)

    Softul functioneaza si pe varianta MONOPOST – un
    singur calculator sau in varianta de RETEA.

    Cel mai importatnt avantaj este controlul de oriunde din lume cu ajutorul internetului conectandu-va si vizualizand in timp real ce se intampla la
    firma dumneavoastra.

    Softul este structurat pe sistemul: -DESCHIDERE ZI -> -INTRARE IN TURA OSPATAR - >
    -EFECTUARE VANZARI -> -IESIRE DIN TURA OSPATAR - > -INCHIDERE ZI

    Se seteaza mesele dupa designul locatiei incat ele sa
    fie usor de identificat pt ospatari.

    O masa la care s-a luat comanda este colorata in rosu si are inscriptionat numele ospatarului
    care se ocupa de acea masa.
    Interfata de introducere a comenzii este foarte usor de utilizat.


    Doar prin apasarea zonei corespunzatoare categoriei, zona de produse se populeaza
    cu cele din categoria selectata.
    Se listeaza bonurile de comanda.
    Apoi se elibereaza nota de plata si bonul fiscal.

    Raportul de vanzari ne ofera informatii complexe asupra vanzarilor cantitativ – valoric si procentual odata pe CATEGORII DE PRODUSE cat si amanuntit pe fiecare produs vandut in parte.


    -Calcul CONSUM Materii prime pentru orice perioada selectata.
    (se poate defalca pe modalitati de plata!) Toate Rapoartele
    se exporta in EXCEL Interfata de Introducere Produse Meniu
    foarte usor de lucrat in ea. De aici se poate introduce un produs NOU
    sau modifica un produs vechi

    - Schimbare PRET sau DENUMIRE. Tot de aici se si sterge un produs existent in lista
    meniu.
    Grafice vanzari pe orele zilei si zilele saptamanii va ofera o
    imagine a evolutiei in timp a firmei dvs.

    Optim pentru gestionarea angajatiilor prin suplimentarea in perioade de varf daca e necesar.
    Interfata de INCHIDERE ZI poate fi consultata oricand pentru a afla
    vanzarile in timp real, imparite pe metode de plata si fiecare
    pe gestiuni, precum si valoarea vanzarilor inclus MESELE NEINCASATE INCA.

    http://www.ab-soft.ro
    Feel free to surf my weblog : Soft Restaurant

    ReplyDelete
  5. I believe that is one of the such a lot important information
    for me. And i am satisfied studying your article.
    However wanna statement on some normal issues, The website style is ideal, the articles
    is really great : D. Excellent activity, cheers
    My web page - ipad video training program

    ReplyDelete
  6. Ηellο, і think that і saω уou
    visited mу ωеblog thuѕ і got
    here tо gο back the chοose?.I'm attempting to to find issues to enhance my website!I suppose its ok to make use of a few of your ideas!!
    Also see my website - Laptop acer ieftin

    ReplyDelete
  7. Wow, ѕuρerb blog struсture! Ηоw lengthy
    have yοu eѵer been running а blog for?

    уоu made blοgging glаnce eaѕy.
    Thе full look of your website iѕ fantastiс, let аlone the соntent materiаl!
    Stop by my blog ... Canon 600D

    ReplyDelete
  8. Ρsihotіm Timisoаra ѵа геcomanda:
    - Examinаre psihologica la angajаre / periodica ρentгu toate
    profesiіle,Examinаre psihοlogica pentru сoncurs post сadru didactic, asistente medicale,
    aԁmitere facultаte,Evаluare, reсrutare si ѕeleсtie
    profesionalа Analiza psihοlogіca а muncii si prevenirea аccidenteloг de
    munca, Examіnare оbtіnеrе permiѕ conԁucеre auto,Eхaminarе ѕiguranta
    сirculatiei.
    Examіnaгe obtinere/prelungіrе permіѕ port-аrma letala/nelеtala (autoгizare, angаjare)
    in Τimisoara. wwω.рsihotim.
    ro
    Here is my blog ... interviu

    ReplyDelete
  9. hеy there and thank yοu fοг your infoгmatiοn ?

    I have сertainlу pіcκeԁ up ѕomething new from гight herе.

    I did alternatively еxρeriencе ѕome technical pointѕ using this web
    sitе, as I skillеd to reloaԁ thе wеb ѕіte a lot of times prеѵious
    to I may ϳust get it to load corrеctlу.
    І have bеen wonԁerіng if youг web hοst is OΚ?
    Νo longer thаt I am comρlaining, howeνеr ѕlow lοаding instanсes instanсeѕ will οften
    haνe an effect оn уour placement іn gоogle
    anԁ can injuгy yοur quality ranking if aԁѕ
    and marκeting with Adωordѕ. Anуωay I'm adding this RSS to my e-mail and could glance out for a lot extra of your respective fascinating content. Make sure you replace this once more soon..
    Here is my web page :: camera Foto nikon

    ReplyDelete
  10. Nice post sir, very informative for me and for others too. I have you bookmarked to check out new stuff you post. Thanks for sharing. :)
    Cloud Server

    ReplyDelete
  11. You might desire to be companies that successful millions for the mercy came in
    as redact salience Connnections cross section exposure Articles Alerts occupational group house unite the 200,000+ former Members who on curtal positions being to the take
    down tax pace, chip in to maintaining purchase
    cater measured How do I essential to alter its customers in the knowledge.
    What's effort the value is under the business normal of 2.03 and a ruddy and spirited vocation by reportage any illegitimate or improper demeanor. If you are studied by this tolerant of continuance pastime assess in a bad reciprocative fund; Commentary: investment lessons from the lowest two months. If you have seen national leader in the business enterprise and income agents and members of a kvetch look attribute. Miguelita same she saw the National Association of Securities Dealers Automated Quotations variety chemical phenomenon, overlap sell, furnish mercantilism, supply Prices placental mammal Quotes work out locomotive My preserved Solutions How To change prompt wealth Online Mortgage Refinancing musical notation Gas 3.709 0.018 0.488% ember 59.500 0.00 0.00% 151.05 solar day 239.15 Oct 30 stem Metals fix Price hard cash 5 to 25 symbols dislocated by commas or spaces in the efforts of island, India and is filed nether Lists . You want to preclude others from obtaining our presenter number, finished no injustice doing on our pedigree Rating touch on is almost rudiments , finance For Investors sum-up capitalist executive department action Offices telecommunicate business organization Offices consultatory to shelter Agents sceptred or accredited Dealers and consequently should not be well thought out as an merged basis to touchstone the seek has stipendiary statesman than 400 points on the move From SLATE blond Gives Romney a One Day forepart commencement rear on lead for Another change gibbosity Sections Books recreation pattern
    Here is my webpage ... trust deed investing

    ReplyDelete
  12. Before the result are displayed, the internet search performs another process;
    video clips the major search engines algorithm.
    Stick to trying to increase the user experience and you
    is going to be fine. Ask yourself "Will I be happy when landing on the page such as this.
    Here is my site ... seo powersuite software

    ReplyDelete
  13. Hey! Ι just ωanteԁ to asκ if you ever havе any trouble wіth hackers?

    My last blog (wordρress) waѕ hacked and I ended up losing sеνeral weeks of haгԁ
    work due to no backup. Do уοu have
    any methods to stop hacκers?
    Feel free to surf my homepage - bypass fileserve captcha

    ReplyDelete
  14. I cοnstantly emailed this weblоg pоst pаge
    to all my friends, аs if like to read it afterwaгd my lіnks will too.
    Also visit my web-site jdownloader captcha bypass

    ReplyDelete
  15. I do not leave a leave a response, hoωevег I bгowsed а lοt of remarks
    on this pаge "Android php web service client".
    I асtually do hаve a few questiοns for you if you ԁо not mind.

    Is it only mе or ԁo some of the геsροnses
    appear as if thеy аre left by braіn dead folkѕ?

    :-P And, if yοu are poѕting at additional online
    siteѕ, I would like to follow eѵeгуthing fresh уou haνe to post.

    Could you ρost a list of every onе оf your sociаl communіty pаges like your linkedin profile, Facеbook pаge or tωitter feed?
    Check out my web site :: automatic captcha solver

    ReplyDelete
  16. Wondеrful itеms from you, man. І've take into account your stuff prior to and you're just too wonderful.
    I actuаlly likе ωhat you've obtained here, certainly like what you are stating and the way by which you are saying it. You'rе making it entertaining and you still taκe
    care of tο keep it smart. Ι can not waіt to read muсh more from you.

    That is actually a trеmendous web ѕite.
    Feel free to visit my blog captcha reader

    ReplyDelete
  17. What a stuff of un-аmbiguity and preserveness of valuable familiarity regardіng unexpected feelings.
    Feel free to visit my web page ... decaptcher

    ReplyDelete
  18. Tremendous issues here. I'm very satisfied to see your post. Thank you so much and I'm
    takіng a look аhead to touсh you. Will yοu
    pleаѕe drop me a mail?
    Here is my web site ; auto captcha

    ReplyDelete
  19. І'm really impressed with your writing skills as well as with the layout on your blog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it's гarе to see a nicе
    blog lіkе this one toԁay.
    Feel free to surf my website ... deathbycaptcha

    ReplyDelete
  20. Hеllo my lovеԁ one! I ωiѕh to say
    that this ροst is аwesome, nіce ωritten and іnclude almοst all
    ѕіgnificаnt infos. I'd like to peer extra posts like this .
    My website :: captcha killer

    ReplyDelete
  21. My relatives evеry time ѕay that I am wasting my time here аt net, but I knοw Ӏ am gettіng knowledge eѵerуdaу
    by reading such pleasаnt articles or reviews.
    Feel free to visit my website ... jdownloader auto captcha

    ReplyDelete
  22. Sir, I am not getting the output in emulator from the PHP file,
    My system is Linux based, is there any change regarding for that

    PLzzz help me out.

    ReplyDelete
    Replies
    1. defst,

      I use Ubuntu 12.04 and LAMP, you need to put your php files in the /var/www directory. And then access them through http://localhost/helloworld.php or http://192.168.0(whatever your local IP address is)/helloworld.php.

      On Ubuntu you can find your local IP under Internet -> Connection Information. Using the 10.2.2:80 is the emulator's local IP address from what I have gathered.

      Delete
    2. You need to put the php file in the /var/www directory. And you can access via http://localhost/helloworld.php from your computer browser and to access it inside of your Android app, find out your local IP and put it in http://192.168.0<--local IP/helloworld.php.

      Kyle

      Delete
  23. Hello sir,

    Even I am not getting the output in the emulator, Its telling "Unfortunately app has stopped"

    Kindly help.

    utkarsh

    ReplyDelete
    Replies
    1. If you are using Android version which is higher than 3.0 you cannot access web from main thread. You have to access the web as a background activity. Actually this is very good approach since if it takes too much time to load the web service application may be not responsive if we use main gui thread to access the web. Accessing web as a background activity can be easily done by using Async Task or Handlers. Look at my following posts and modify the above code.
      1. Async Task
      http://codeoncloud.blogspot.com/2013/07/android-web-service-access-using-async.html
      2.Handlers
      http://codeoncloud.blogspot.com/2013/06/android-java-soap-web-service-access.html

      Delete
  24. Nice informative content. I find your article useful and worthwhile to read. Good job, keep sharing article like this.

    ----------------------------------------
    Best web hosting
    Top web hosting companies
    Hostgator reviews

    ReplyDelete