RSS

Connection between PHP (server) and Android (client) Using HTTP and JSON

21 Apr

The main reason for taking a scripting language like PHP is because of the interaction with databases it can offer. In this tutorial I will show you how to use PHP and the MySQL database to retrieve information from the server. For making connection to PHP script, we will  use HTTP protocol from the android system. To implement this tutorial you should have basic knowledge of how to run PHP script and start server.  If we talk about client-server architecture, client is Android device and in server side there is a combination of PHP Script and MySQL. In short, PHP Script sits in middle as shown in image.

Android - PHP - MySQL Scheme

We will use JSON (JavaScript Object Notation) format. JSON is a lightweight text-based open standard designed for human-readable data interchange.

How json will be used in our application.
- When android application will execute, it will connect android device to PHP Script.
- PHP Script will fetch data from the database. It will encode it into json format and send it to the device.
- Now, android application will get these encoded data. It will parse the data and display it on android device.

Here is the implementation detail.
In MySQL create database FOOD. In database create table FOOD. This table consists of two columns. First is FOOD_ID, which is auto_increment and primary_key and having data type INT. Second column is FOOD_NAME, which has data type VARCHAR(20).

We want to retrieve food name from our table FOOD that starts with A.
The PHP code will be very simple:
- Connect to the database
- Run an SQL query, with a WHERE block depending on data from POST/GET values
- Output it in JSON format

For example we will have this functionality in food.php:

<?php
  mysql_connect("127.0.0.1","root","12345");
  mysql_select_db("FOOD");
  $sql=mysql_query("select * from FOOD where FOOD_NAME like 'A%'");
  while($row=mysql_fetch_assoc($sql)) $output[]=$row;
  print(json_encode($output));
  mysql_close();
?>

In our Android application,
- Use a HttpPost to get the data,
- Convert response to string
- Parse JSON data, and use it as you want

The whole code of retrieving data from server to our android application is shown as below.

public class food extends ListActivity {
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		String result = null;
		InputStream is = null;
		StringBuilder sb=null;
		String result=null;

		//http post
		try{
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		}catch(Exception e){
			Log.e("log_tag", "Error in http connection"+e.toString());
		}
	
		//convert response to string
		try{
			BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
			sb = new StringBuilder();
			sb.append(reader.readLine() + "\n");
			String line="0";
	     
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			
			is.close();
			result=sb.toString();
			
		}catch(Exception e){
			Log.e("log_tag", "Error converting result "+e.toString());
		}

		//paring data
		int fd_id;
		String fd_name;
		try{
      	jArray = new JSONArray(result);
      	JSONObject json_data=null;
      	
      	for(int i=0;i<jArray.length();i++){
				json_data = jArray.getJSONObject(i);
				fd_id=json_data.getInt("FOOD_ID");
				fd_name=json_data.getString("FOOD_NAME");
      	}
      	
		}catch(JSONException e1){
			Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
		}catch (ParseException e1){
			e1.printStackTrace();
		}
	}
}

Another example Using JSON between PHP and Android:

- JSON Code:

JSONObject j = new JSONObject();
j.put("engineer", "me");
j.put("date", "today");
j.put("fuel", "full");
j.put("car", "mine");
j.put("distance", "miles");

- Android code:

String url = "http://www.server.com/phpfile.php";
Map<String, String> kvPairs = new HashMap<String, String>();
kvPairs.put("vehicle", j.toString());
HttpResponse re = HTTPPoster.doPost(url, kvPairs);
String temp = EntityUtils.toString(re.getEntity()); 

if (temp.compareTo("SUCCESS")==0) {
   Toast.makeText(this, "Sending complete!",Toast.LENGTH_LONG).show();
}

- Class code:

public static HttpResponse doPost(String url,Map<String, String> kvPairs) throws ClientProtocolException, IOException{
   HttpClient httpclient = new DefaultHttpClient();
   HttpPost httppost = new HttpPost(url); 

   if (kvPairs != null &amp;&amp; kvPairs.isEmpty() == false) {
       List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(kvPairs.size());
       String k, v;
       Iterator<String> itKeys = kvPairs.keySet().iterator(); 

       while (itKeys.hasNext()) {
              k = itKeys.next();
              v = kvPairs.get(k);
              nameValuePairs.add(new BasicNameValuePair(k, v));
       } 

       httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
   } 

   HttpResponse response;
   response = httpclient.execute(httppost); return response;
}

Happy coding :)

 

More tutorial, click the link bellow:

The Simplest Way to POST Parameters Between Android and PHP (Android SDK)

About these ads
 
131 Comments

Posted by on April 21, 2011 in Android, web programming

 

Tags: , , , ,

131 responses to “Connection between PHP (server) and Android (client) Using HTTP and JSON

  1. Zan

    April 21, 2011 at 20:53:49

    Hello!

    Thank you for this tutorial!
    There is missing code at food.php … :) Is this mistake or something else ?

     
    • fahmirahman

      April 22, 2011 at 00:31:56

      Sorry for that, I thought it was wordpress bug’s whe I try to update the articles. It was fixed now.. thx for your feedback :)

       
      • leah

        June 11, 2011 at 22:50:38

        what’s missing there? i used the codes above but it is not working.. it only outputs the URL.. please help.. i badly needed your help.. im doing a project and i want to finish it ASAP because i am running out of time.. help me please :( anyone?

         
    • U

      January 28, 2012 at 15:53:26

      I beginer in android development. I got a task to store and retrive data to/from mysql database. I need a basic steps using eclipse. I use the above code, but i dont know where to place or put up the php file.

       
    • Umesh Suryawanshi (GH Raisoni Nagpur)

      January 28, 2012 at 15:56:54

      I beginer in android development. I got a task to store and retrive data to/from mysql database. I need a basic steps using eclipse. I use the above code, but i dont know where to place or put up the php file. Whether php file store in our project folder or in mysql database folder

       
    • sri..

      September 25, 2012 at 14:45:52

      Is it possible to connect mysql with out PHP (server)..

       
  2. Zan

    April 24, 2011 at 17:49:49

    Thank you for fast reply ;)
    I have another question… I am working on an application, which must send three parameters to PHP server.. That PHP server must write them into mysql database. Now I am having big problems sending these data over HTTP from Android to my PHP server.. I tried so many tutorials and it doesn’t work.. Is there any option you could send me very basic sample code, sending data to server and receive it in php file?

    Thank you very very much!!!! ;)

     
  3. Santosh

    April 27, 2011 at 16:49:39

    Hello…
    I’m doing an project based on busroute finding application for android where we need give input as busNumber to the application the same have display bus stops list coming under that bus number
    For database i’m using mysql and php for scripting.Now i’m posting my php code to u where in query busNumber should get from the android UGI what the modification i have to do for this??
    If u provide ur email id i’ll send my complete source code to u plz help me on this………..thank u…

    php source

    in busNumber place of the query automatically it has to take input from UI

     
    • fahmirahman

      April 27, 2011 at 16:54:56

      Can you draw me the flowchart?

       
      • Santosh

        April 27, 2011 at 16:58:49

        please provide me ur mail id i’ll send all details……

         
    • narender

      June 15, 2012 at 12:57:11

      plese send me source code

       
  4. fahmirahman

    April 27, 2011 at 17:00:33

     
  5. Santosh

    April 27, 2011 at 17:02:21

    ok thanks i’ll send all details along with my source code, please help me……

     
  6. Santosh

    April 27, 2011 at 17:13:10

    ok thaks a lot…see it has been sent

     
  7. Rohit

    April 28, 2011 at 17:02:50

    hi,
    i got a problem that when i receeive data in my application it always show a single item .how can i access multiple rows.

     
  8. vikas

    May 4, 2011 at 01:31:31

    i want to retrieve data from server. php file is working fine i e data is being received to php…but i want that data to be on my android phone. can somebody help me in retrieving data from server.

     
  9. vikas

    May 4, 2011 at 15:10:37

    i am not getting your …point if ill mail you my project can you pls do it for me

     
  10. Ahmed El-Sharkasy

    May 27, 2011 at 02:45:32

    is there any preference to use cakephp instead of raw php?

     
  11. Andre

    June 3, 2011 at 21:58:38

    Hi can you tell me how I can put retrieved data into a ListView? I’m using this:

    String name;
    try{
    jArray = new JSONArray(result);
    JSONObject json_data=null;
    for(int i=0;i<jArray.length();i++){
    json_data = jArray.getJSONObject(i);
    name=json_data.getString("name");
    }
    }catch(JSONException e1){
    Toast.makeText(getBaseContext(), "Nessun quiz trovato" ,
    Toast.LENGTH_LONG).show();
    } catch (ParseException e1) {
    e1.printStackTrace();
    }

    // first tab
    TabSpec ts = myTabHost.newTabSpec("TAB_TAG_1");
    ts.setIndicator("Available quiz",
    rs.getDrawable(R.drawable.quiz_selected));
    ts.setContent(new TabHost.TabContentFactory() {

    public View createTabContent(String tag) {

    /* ArrayList appAL = new ArrayList(50);
    String stringaInizio = “;”;
    String stringaFine = “;”;
    appAL = fullArrayInt(appoggio, stringaInizio, stringaFine);*/

    ArrayAdapter adapter = new ArrayAdapter(
    MainMenuActivity.this,
    android.R.layout.simple_list_item_1);

    ls1.setTextFilterEnabled(true);
    ls1.setAdapter(adapter);

    return ls1;

    }

    });
    myTabHost.addTab(ts);

    Well, i want to put the retrieved data inside of that ArrayAdapter but i don’t know what to put after the context (MainMenuActivity.this, R.layout.simple….. )

    Thanks for your help!

     
  12. Peter

    June 17, 2011 at 21:28:16

    Hello, in your PHP code, does “print(json_encode($output))” send output data to Android client ? I thought “print” command is used for displaying purpose. Please, correct me if am wrong. Thanks

     
    • fahmirahman

      June 17, 2011 at 21:34:33

      Yes you right.. I use the “print” command in php..

       
      • krishna

        March 15, 2012 at 17:00:28

        crashing…….crashing…..please help m working on android
        2.3 sdk i have also tried with diif versions…i dont have any errors please help

         
  13. sush

    June 27, 2011 at 14:57:32

    hello,

    I want to do client server programme for android using json..
    Can anyone help…

     
  14. john

    June 27, 2011 at 16:39:16

    could you just put in ur whole source code with folder division as in eclipse. .. that will help a lot and will be much easier to understand

     
  15. john

    June 27, 2011 at 16:42:34

    the project produces a force close error on the 2.1 android emulator

     
    • sush

      June 28, 2011 at 12:39:02

      it also shows the same error in version 2.2 android emulator

       
  16. Middle East Conflict

    July 2, 2011 at 03:11:20

    A powerful share, I just given this onto a colleague who was doing a little analysis on this. And he actually purchased me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the deal with! But yeah Thnkx for spending the time to debate this, I really feel strongly about it and love studying more on this topic. If potential, as you develop into expertise, would you mind updating your blog with more details? It is highly useful for me. Massive thumb up for this weblog publish!

     
  17. Asish

    July 8, 2011 at 15:07:16

    How to do this in background mode??? Any Help Appreciated

     
  18. Pronájem chalupy bezrealitky

    July 9, 2011 at 01:37:07

    Can I post your post to my wordpress blog? I’ll add a one-way link to your forum. That’s one actually nice post.

     
  19. Juan

    July 9, 2011 at 17:48:02

    Hi, thanks for the tutorials are very helpful.

    I want to ask some help. Turns out I have a server on localhost: http://localhost/backend/json.php and json.php file is as follows:

    $pelicula);
    }
    }

    // now, the output in JSON format:
    header(‘Content-type: application/json’);
    echo json_encode(array(‘descargas’=>$descargas));

    // disconnect from the db
    @mysql_close($link);

    ?>

    I need to know how to get the data as a list json.php. I have proven with your tutorial but I have left.

    Would be very grateful if you could help me.

    Sorry for my English, I’m Spanish xD.

     
  20. Necixy

    July 18, 2011 at 17:08:38

    The variable “Result” has been declared two times, which produces error.

     
  21. android beginner

    July 25, 2011 at 12:44:57

    i get an ‘unexpectedly stopped’ error.. it asks to force close… wat is the reason for it, n how can i resolve it???

     
  22. let's get this working

    August 9, 2011 at 01:40:45

    Also nameValuePairs is undeclared and undefined

     
  23. sush

    August 17, 2011 at 13:25:00

    I would like to know more about streaming part… can anyone provide code for streaming video for android.. i am new to it.

    thanks in advance..

     
  24. Sam

    August 25, 2011 at 04:18:40

    Hey, thanks for your interesting post, I was wondering if you can provide an example where android device wants to update server side’s database. Assume we have a content provider on android device and we would like to send data upon insertion to the database on client side (Android device) or upon update on the client. Curious to find out how exactly the other way around works for this example.

    Thanks,
    Sam

     
  25. sajol

    August 29, 2011 at 11:37:30

    hi,
    this is my php code for this tutorial.but does not show any output.
    plzzzzzzzzzzzzzzzzz help me as soon as possible

     
    • bharathyp

      January 30, 2012 at 20:25:30

      are u using the same code as above?

       
  26. cellulite

    October 3, 2011 at 02:19:48

    I get pleasure from, result in I discovered exactly what I was looking for. You’ve ended my 4 day lengthy hunt! God Bless you man. Have a nice day. Bye

     
  27. banti

    October 10, 2011 at 19:36:38

    hii am i using thiss artical bt it showw errorr

    null and can not covert in jarrayyy
    can you helpp me is some error on avobe articall if any please explainn

     
  28. banti

    October 11, 2011 at 11:36:15

    i cannot read my jeson encoded data in my android class my result string return null

     
  29. yudha

    October 20, 2011 at 12:47:07

    i have web page data scraper in php.. how to fetch data from php to android apps,if the php is in localhost?

     
  30. Daniel

    November 10, 2011 at 06:26:25

    Hi,
    thanks for the tutorial.
    Do you have an idea how to make it finish the activity if it cant connect instead of force closing?

     
  31. Comp.Eng

    November 15, 2011 at 19:07:22

    can you plz give me the whole server code in php ??

     
  32. kusi

    December 1, 2011 at 16:26:32

    Thanks for the Nice explanation..But there are so many mistakes in the code..This post is targeted towards beginners but it gets difficult for people like us to get rid of all these errors. It would have been better if you had copied the exact code from this site and tested it on your system..

     
  33. Krishna

    December 8, 2011 at 08:03:07

    Hi
    Is it possible to store and retrieve image from MySQL database using json

     
  34. raj

    January 9, 2012 at 15:38:24

    thanks for this tutorial

     
  35. kumar

    January 10, 2012 at 22:09:01

    Hi,

    I want to send data from android to google docs (spreadsheet) . how can i do this..

     
  36. hirut

    January 26, 2012 at 16:08:13

    hi every one
    how android application and server that have asp.net application connect

     
  37. Shashank

    February 8, 2012 at 17:09:40

    hi ! gr8 article! could u provide a similar example where the server happens to be google app engine and how to retrieve the data and display in a list view on the android client??

     
  38. Tony

    February 10, 2012 at 11:50:58

    How can I set the nameValuePairs?
    because the code is missed…

     
  39. Tony

    February 10, 2012 at 16:39:27

    ummm

    I have finished the connection

    but how can get the sub-data in the data from the php?

     
  40. Conor

    February 12, 2012 at 21:11:42

    There are some errors in the code, for example in the line:

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    what is nameValuePairs? it is undeclared and unclear as to what it is. Any help would be great, thanks!

     
  41. ranjit

    February 13, 2012 at 17:30:24

    hii.
    plz tell me where to store the php file and mysql database in system?
    actually i am new ..

    plz help me.

     
  42. Papa

    February 15, 2012 at 23:55:25

    please i follow the tutorial great but where to put the php code i am andoid biginer

     
    • pretty

      February 24, 2012 at 02:07:51

      php code goes to your server side. For me i have got a wamp server and have put my php file in the www directory so that it can be accessed via http://127.0.0.1/food.php as in line14

       
  43. danny

    February 17, 2012 at 13:38:43

    As usual it doesnt work and the code from the first example is not complete.

    I print the whole code here:

    package mysqlconnect.pack;

    import android.app.Activity;
    import android.os.Bundle;
    import android.app.ListActivity;

    public class MysqlconnectActivity extends ListActivity {

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    String result = null;
    InputStream is = null;

    StringBuilder sb=null;

    String result=null;

    //http post

    try{

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(“http://127.0.0.1/food.php”);

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();

    }catch(Exception e){

    Log.e(“log_tag”, “Error in http connection”+e.toString());

    }

    //convert response to string

    try{

    BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1″),8);

    sb = new StringBuilder();

    sb.append(reader.readLine() + “\n”);

    String line=”0″;

    while ((line = reader.readLine()) != null) {

    sb.append(line + “\n”);

    }

    is.close();

    result=sb.toString();

    }catch(Exception e){

    Log.e(“log_tag”, “Error converting result “+e.toString());

    }

    //paring data

    int fd_id;

    String fd_name;

    try{

    jArray = new JSONArray(result);

    JSONObject json_data=null;

    for(int i=0;i<jArray.length();i++){

    json_data = jArray.getJSONObject(i);

    fd_id=json_data.getInt("FOOD_ID");

    fd_name=json_data.getString("FOOD_NAME");

    }

    }catch(JSONException e1){

    Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();

    }catch (ParseException e1){

    e1.printStackTrace();

    }

    }

    }

    I get tons of errors in eclipse, the first one:
    inputstream can not be resolved as a type.

    pleas help,

     
  44. danny

    February 17, 2012 at 14:03:56

    sorry i am just a beginner in android programming and i see i have to import packages:

    import java.io.InputStream;
    import org.apache.http.client.HttpClient;
    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import android.app.Activity;
    import android.os.Bundle;
    import android.app.ListActivity;
    import android.util.Log;
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import org.json.JSONArray;
    import org.json.JSONObject;
    import org.json.JSONException;
    import android.widget.Toast;
    import android.net.ParseException;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import java.util.List;
    import org.apache.http.NameValuePair;
    import java.util.ArrayList;

    doesnt load though, is sais:

    sorry! process name.pack has stopped unexpectedly please try again

     
  45. moetez

    February 22, 2012 at 19:18:32

    do you have a tutorial on how to connect between php and android using sql server 2008 ?

     
  46. rifatkirac

    February 23, 2012 at 18:27:29

    Thansk a lot I hadnt known before I saw it. Thanks a lot .
    I have a project know And I will use this . Thanks again

     
  47. aimi

    March 9, 2012 at 12:58:07

    hye i’m the begginer…to start the php…u use wamp or xamp?…sory for asking this stupid question.. becoz i ask around no body know it… i want to use php as a server.. and android as a cliant..but don’t know how to start in php part..it i should install xampp or wamp…

     
    • Alex

      March 13, 2012 at 20:04:42

      whatever you want. I like xampp ;)

       
  48. krishna

    March 13, 2012 at 14:10:33

    it says nameValuePairs cant be resolved to variable……please help

     
  49. krishna

    March 13, 2012 at 15:07:05

    resolved but its crashing…asking for force close….please help…thanks in advance

     
    • Arikrishnan

      March 14, 2012 at 02:48:06

      @krishna: put this line in your activity
      ArrayList nameValuePairs = new ArrayList();

       
  50. Arikrishnan

    March 14, 2012 at 02:51:50

    hey guys it showing error in this line like ” value of string can not converted into JSONArray “.. jArray = new JSONArray(result);

    Any idea.. Help me please .. Thanks in advance.. i just copied and pasted above code..

     
  51. krishna

    March 15, 2012 at 13:33:20

    when i run it on emulator its crashing(sya application process stopped unexpectedly)….please help…thnx in advance

     
  52. krishna

    March 16, 2012 at 16:35:27

    its working now i just replaced ListActivity by Activity…………..can anyone please give me link or code about when i fetch data from database i should able to click on text to go to next activity…example suppose we have book store names in database after we get result from above code then if i click on perticular book shop name it should go to next activity….thnx in advance

     
  53. Ashish Kamath

    March 22, 2012 at 17:05:46

    I am a beginner at android..plz help me for the connection..my code is as follows..i want 2 display list of atms through this code bt i am nt able 2 connect it to db..plz help

    atm.java

    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.Activity;

    import android.content.Intent;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    public class atm extends Activity {
    /** Called when the activity is first created. */
    public TextView txt;
    public Button b;
    public String Name[]=new String[50];
    public String Address[]=new String[50];
    public String Email_id[]=new String[50];
    public String Landmark[]=new String[50];
    public String Website[]=new String[50];
    public String Specialtiy[]=new String[50];
    public int Latitude[]=new int[20];
    public int Longitude[]=new int[20];
    public int ContactNo1[]=new int[15];
    public int ContactNo2[]=new int[15];
    public int FaxNo[]=new int[15];
    public int n;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.h);
    // Create a crude view – this should really be set via the layout resources
    // but since its an example saves declaring them in the XML.
    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    txt = new TextView(getApplicationContext());
    rootLayout.addView(txt);

    // Set the text and call the connect function.
    // txt.setText(“Connecting…”);
    //call the method to run the data retrieval
    getServerData(KEY_121);
    for(int i=0;i<n;i++)
    {
    txt.setText("NAME:-"+Name[i]);
    txt.append("\n");
    txt.append("ADDRESS:-"+Address[i]);
    txt.append("\n");
    txt.append("LANDMARK:-"+Landmark[i]);
    txt.append("\n");
    txt.append("LATITUDE:-"+Latitude[i]);
    txt.append("\n");
    txt.append("LONGITUDE:-"+Longitude[i]);
    txt.append("\n");
    txt.append("CONTACT NUMBERS:-"+ContactNo1[i]+"\t"+ContactNo2[i]);
    txt.append("\n");
    txt.append("FAX:-"+FaxNo[i]);
    txt.append("\n");
    txt.append("WEBSITE:-"+Website[i]);
    txt.append("\n");
    txt.append("SPECIALITY:-"+Specialtiy[i]);
    txt.append("\n");
    }

    b = new Button(getApplicationContext());
    b.setText("SHOW ON MAP");
    rootLayout.addView(b);

    setContentView(rootLayout);

    //Btn = (Button) findViewById(R.id.btn2);

    b.setOnClickListener(new OnClickListener()
    {
    public void onClick(View v)
    {
    Bundle b =new Bundle();
    b.putStringArray("key1",Name);
    b.putStringArray("key2",Address);
    b.putStringArray("key3",Landmark);
    b.putStringArray("key4",Email_id);
    b.putStringArray("key5",Website);
    b.putStringArray("key6",Specialtiy);
    b.putIntArray("key7", Latitude);
    b.putIntArray("key8", Longitude);
    b.putIntArray("key9", ContactNo1);
    b.putIntArray("key10",ContactNo2);
    b.putIntArray("key11", FaxNo);

    Intent i=new Intent(getApplicationContext(), Map.class);
    i.putExtras(b);
    startActivity(i);

    }
    });
    }

    public static final String KEY_121 = "";//i use my real ip here

    private String getServerData(String returnString) {

    InputStream is = null;

    String result = "";
    //the year data to send
    ArrayList nameValuePairs = new ArrayList();
    nameValuePairs.add(new BasicNameValuePair(“latitude1″,”19″));
    nameValuePairs.add(new BasicNameValuePair(“latitude2″,”20″));
    nameValuePairs.add(new BasicNameValuePair(“longitude1″,”72″));
    nameValuePairs.add(new BasicNameValuePair(“longitude2″,”73″));

    //http post
    try{
    System.out.println(“before http”);
    HttpClient httpclient = new DefaultHttpClient();
    System.out.println(“1″);
    HttpPost httppost = new HttpPost(KEY_121);
    System.out.println(“2″);
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    System.out.println(“3″);
    HttpResponse response = httpclient.execute(httppost);
    System.out.println(“4″);
    HttpEntity entity = response.getEntity();
    System.out.println(“5″);
    is = entity.getContent();

    }catch(Exception e){
    Log.e(“log_tag”, “Error in http connection “+e.toString());
    }

    //convert response to string
    try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1″),8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
    sb.append(line + “\n”);
    }
    is.close();
    result=sb.toString();
    }catch(Exception e){
    Log.e(“log_tag”, “Error converting result “+e.toString());
    }
    //parse json data
    try{
    JSONArray jArray = new JSONArray(result);
    n=jArray.length();
    for(int i=0;i<jArray.length();i++)
    {
    JSONObject json_data = jArray.getJSONObject(i);

    //Get an output to the screen
    returnString += "\n\t" + jArray.getJSONObject(i);
    Name[i]=json_data.getString("Name");
    Address[i]=json_data.getString("Address");
    Landmark[i]=json_data.getString("Landmark");
    Email_id[i]=json_data.getString("Email_id");
    Website[i]=json_data.getString("Website");
    Specialtiy[i]=json_data.getString("Specialtiy");
    Latitude[i]=json_data.getInt("Latitude");
    Longitude[i]=json_data.getInt("Longitude");
    ContactNo1[i]=json_data.getInt("ContactNo1");
    ContactNo2[i]=json_data.getInt("ContactNo2");
    FaxNo[i]=json_data.getInt("FaxNo");

    }
    }catch(JSONException e){
    Log.e("log_tag", "Error parsing data "+e.toString());
    }
    return returnString;
    }

    }

    map.java

    import java.util.List;

    import android.os.Bundle;

    import com.google.android.maps.GeoPoint;
    import com.google.android.maps.MapActivity;
    import com.google.android.maps.MapController;
    import com.google.android.maps.MapView;
    import com.google.android.maps.Overlay;
    import com.google.android.maps.OverlayItem;
    //import android.content.Context;
    import android.graphics.drawable.Drawable;
    /*import android.location.Location;
    import android.location.LocationListener;
    import android.location.LocationManager;
    import android.widget.Toast;*/

    public class Map extends MapActivity {
    /** Called when the activity is first created. */
    private MapView mapView;

    private static final int latitude = 192435414;
    private static final int longitude = 728555764;
    //public static double EARTH_RADIUS_KM = 6384;// km
    public int n;
    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.screen1);

    mapView = (MapView) findViewById(R.id.mapView);
    mapView.setBuiltInZoomControls(true);

    List mapOverlays = mapView.getOverlays();
    Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
    CustomItemizedOverlay itemizedOverlay = new CustomItemizedOverlay(drawable, this);

    Bundle b=this.getIntent().getExtras();
    String[] Name=b.getStringArray(“key1″);
    String[] Address=b.getStringArray(“key2″);
    /* String[] Landmark=b.getStringArray(“key3″);
    String[] Email_id=b.getStringArray(“key4″);
    String[] Website=b.getStringArray(“key5″);
    String[] Specialtiy=b.getStringArray(“key6″);*/
    int Latitude[]=b.getIntArray(“key7″);
    int Longitude[]=b.getIntArray(“key8″);
    int ContactNo1[]=b.getIntArray(“key9″);
    /* int ContactNo2[]=b.getIntArray(“key10″);
    int FaxNo[]=b.getIntArray(“key11″);*/

    n=Latitude.length;
    for(int i=0;i<n;i++)
    {
    GeoPoint point = new GeoPoint(Latitude[i], Longitude[i]);

    OverlayItem overlayitem = new OverlayItem(point,"LOCATION: "+Name[i],"ADDRESS: "+Address[i]+" , "+"CONTACT NUMBER: "+ContactNo1[i]);
    itemizedOverlay.addOverlay(overlayitem);
    }
    mapOverlays.add(itemizedOverlay);
    MapController mapController = mapView.getController();
    GeoPoint point2 = new GeoPoint(latitude, longitude);
    mapController.animateTo(point2);
    mapController.setZoom(3);

    }
    protected boolean isRouteDisplayed() {
    // TODO Auto-generated method stub
    return false;

    }

    }

     
  54. Sandun Dissanayake

    April 3, 2012 at 14:23:08

    Hello,
    How see those Wampserver database data in the Android app…plz help me…

    Thank u.

     
  55. sidzz22

    April 14, 2012 at 18:34:55

    Salam,
    Plzzz help me at android……. i cant get my sql data from server to android…

     
  56. tasomaniac

    May 19, 2012 at 18:35:36

    I am using exactly the same thing in my app. But one thing makes me think a lot.
    A clever user can listen the network and easily get the php file that the program POSTs. The POST values are fragile and I dont want anyone to post outside of my app.
    How can I accomplish this security issue?

     
  57. sandeep

    June 1, 2012 at 15:09:58

    hi i am beginner in android..I have been give to learn JSON for gaming purpose in android could anyone suggest links to refer

     
  58. anshul

    June 6, 2012 at 01:01:19

    i am making an android application that makes use of a client and a server..but i get java.net.socketexception bad file number..what type of error is this and how do solve this error? Is there a way around? p

     
  59. joe

    June 8, 2012 at 20:08:36

    mas fahmi,, bisa gak kalo JSON parsing data yang dari server ke tampilan Googlemap (android) ??

     
  60. Nestor

    June 14, 2012 at 02:48:27

    Alguien que me ayude, ESPANOL estare agradecido

     
  61. Jean-Christoph

    June 20, 2012 at 23:08:06

    I,m tryingthe first example to retrieve data from php server. The scripst stops with “threadid exiting with uncaught exception. I think it’s th layout file that causes the error?

     
    • Jean-Christoph

      June 20, 2012 at 23:09:40

       
  62. Jean-Christoph

    June 20, 2012 at 23:11:19

    I try to post the xml file. no chance. I think it’s the list view with the id android:id=”@android:id/list” ?

     
  63. arpit

    June 26, 2012 at 21:06:15

    its giving error on line
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    nameValuePairs cant be resolved..can u fix it?
    waiting 4 ur kind reply

     
  64. Sai

    September 17, 2012 at 13:22:39

    Search Google

     
  65. sanghati mukherjee

    October 26, 2012 at 17:29:26

    I only want fetch one data that is ID from my table. my querry is :

    SELECT id FROM mytable_name ORDER BY ID DESC
    $sql = mysql_query($query) or die(mysql_error());
    $result=mysql_fetch_assoc($sql);
    json_encode($result);

    The above is php file now in android i want the value of last row ID to use it in my code. only want to fetch one value .. can u please help me out to do this without any array condition or listview.
    I tried the above code but due to array i am not getting one value..

     
  66. sudhakar

    November 6, 2012 at 12:13:40

    It was a nice post. We were able to learn things quickly

     
  67. Tommy

    January 8, 2013 at 00:58:43

    How n00b can i get?

    It doesnt say where to put the code.
    I believe that the visible design should be placed in res->layout->myproject.xml file, and that android-code should be in my main java-file located in com->myproject->myproject.java ?

    However, I get TONS of errors when placing the code in java-file. Most of them i can get rid of by using “quickfixes”(although i dont know if i choose the right ones). But i also get errors that dont get any quickfixes so what to do…

    Is it possible that you can update this post with description to where we should put the code, also if you expect us to actually get errors and to resolve them for us selves, could we get a more detailed description so we understand what should be converted to what aso?

    Have searched the internet for days and have found several tutorials on how to do this but i never get it to work becouse of code-errors, and i do not have enough experiance in java/android to work it out myself.. I use googles ADT with eclipse and open a new project(android project).. Could it be that you use another IDE that causing my errors?

    Is’nt it odd that google’s android development forums/pages doesnt have an “how” to on this subject? or do i just dont know where it is?

     
  68. Gomatesh

    February 5, 2013 at 23:45:48

    Hello i am new to android. I want to implement a login module for my application. i am not able to connect my android and PHP file the appliaction is unfortunately stopping. i ahve designed my layout. jus need to evaluate user…
    help please.

     
  69. ritesh

    March 12, 2013 at 16:20:02

    package com.example.datafetch;
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.List;

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpResponse;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.impl.client.DefaultHttpClient;
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import android.app.ListActivity;
    import android.net.ParseException;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.Toast;

    public class MainActivity extends ListActivity {

    private List nameValuePairs;
    private JSONArray jArray;

    @Override

    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    String result = null;

    InputStream is = null;

    StringBuilder sb=null;

    String result1=null;

    //http post

    try{

    HttpClient httpclient = new DefaultHttpClient();

    HttpPost httppost = new HttpPost(“http://127.0.0.1/chotu/conn.php”);

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    HttpResponse response = httpclient.execute(httppost);

    HttpEntity entity = response.getEntity();

    is = entity.getContent();

    }catch(Exception e){

    Log.e(“log_tag”, “Error in http connection”+e.toString());

    }

    //convert response to string

    try{

    BufferedReader reader = new BufferedReader(new InputStreamReader(is,”iso-8859-1″),8);

    sb = new StringBuilder();

    sb.append(reader.readLine() + “\n”);

    String line=””;

    while ((line = reader.readLine()) != null) {

    sb.append(line + “\n”);

    }

    is.close();

    result1=sb.toString();

    }catch(Exception e){

    Log.e(“log_tag”, “Error converting result “+e.toString());

    }

    //paring data

    int fd_id;

    String fd_name;

    try{

    jArray = new JSONArray(result);

    JSONObject json_data=null;

    for(int i=0;i<jArray.length();i++){

    json_data = jArray.getJSONObject(i);

    fd_id=json_data.getInt("FOOD_ID");

    fd_name=json_data.getString("FOOD_NAME");

    }

    }catch(JSONException e){

    Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();

    }catch (ParseException e){

    e.printStackTrace();

    }

    }

    }

     
  70. coolspirits

    March 14, 2013 at 12:54:10

    hey!! i am trying to make app which will populate the map with stored long/lat values in the database. this db should be accessible to everyone who will use this app!i.e whenever this app is launched ,….. with the internet the map is populated with the long/lat !!!! can you please help how to make this!!!!
    thanks in advance!!

     
  71. krunal

    March 25, 2013 at 00:31:59

    hello sir,

    u have any tutoryal for …
    I have taken spinner and have database in Wamp Server.. I want to get data like Product Name and Product Image from database on spinner in android.

     
  72. refka

    April 6, 2013 at 18:03:38

    i tired to apply this tut (login,registration) with my data base but having json errors

    the registration works when i turn back to my database but it show me msg error on the emulator

    http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/

    please help me to correct it i can send my version ( ref9abm@gmail.com)

    Thanks..

     
  73. Faiz

    May 9, 2013 at 02:10:50

    Hello. Can you provide SQL script for food.php?

     
  74. Mohammed Abbas

    May 14, 2013 at 04:11:31

    really i appreciate that ,,, but i have a question how does the my android device “client” connect with the server by the internet or other connection??

     
  75. Sanjeev Anand

    May 20, 2013 at 15:02:02

    thanks a lot brother…… you solved my problem.. thanks you soooo muchhhhh

     
  76. naughty milfs

    June 21, 2013 at 13:59:47

    This would be the quickest way to get local wiveschaeting.
    As you study the layouts, mimic what they are doing.
    If you want webcam sex, again let others know here.

     
  77. darmowe automaty do gry hot spot online

    June 22, 2013 at 19:43:05

    Hmm is anyone else experiencing problems with the images on this blog loading?
    I’m trying to find out if its a problem on my end or if it’s the blog.
    Any responses would be greatly appreciated.

     
  78. r k jha

    July 18, 2013 at 12:55:17

    pls change the background colour or font colour ………..

     
  79. ブルガリ チョコ

    August 1, 2013 at 08:25:00

    We’ve the Tumblr blog page which can be tied in so that you can this internet site. Your blog page can be interconnected off of the page. I would like to recognise if there is a golf widget or even an issue that I’ll use great website’s page that may indicate great most recently released websites. Definitely not the whole publish, yet it could be only just the actual heading and a backlink to venture to great blog page..

     
  80. imarun92

    September 27, 2013 at 16:29:52

    Reblogged this on Creative Keystrokes and commented:
    Android Application Connection with Server using PHP/JSON

     
  81. karthik

    October 14, 2013 at 17:36:09

    i post my image to server as a string using base64..now i need to get the image from that database and displayed in imageview..Can u send me the code,if you have the solution..

     
  82. James

    December 19, 2013 at 02:29:09

    code is full of errors. For example, where did you define nameValuePairs?

     
  83. Dilip

    January 28, 2014 at 12:20:59

    Hello friend i create one application in that i want to connect my apps to website… database and access and update all record from the apps

     
  84. teeth whitening zoom vs laser

    March 5, 2014 at 22:41:37

    My spouse and I absolutely love your blog and find many of your post’s to be what precisely I’m looking for.
    Do you offer guest writers to write content for yourself?
    I wouldn’t mind composing a post or elaborating on many of the subjects you write regarding here.
    Again, awesome weblog!

     
  85. niyas pavil

    March 13, 2014 at 01:52:25

    can you give me an answer for that how to upload a file from android device to mysql db

     
  86. edward

    March 13, 2014 at 06:47:54

    can sharing the main.xml code for me?

     
  87. fasting benefits health

    March 22, 2014 at 07:44:55

    There’s definately a lot to know about this subject. I really like all the points you made.

     
  88. juicing limes

    March 27, 2014 at 03:52:18

    Hi, I do believe this is an excellent website.
    I stumbledupon it ;) I am going to come back once again since i have book marked it.
    Money and freedom is the best way to change, may you be
    rich and continue to guide other people.

     
  89. vietnam tours package

    March 31, 2014 at 11:19:44

    These are actually fantastic ideas in concerning blogging.
    You have touched some good points here. Any way keep up wrinting.

     
  90. Jonso

    April 1, 2014 at 07:22:40

    hey ,i am using android app to retrieve data from mysql database for the bus management system project.The user should be able know the timetable for the bus ,the time the bus will take to get to the next bus stop,whether the bus is full or not etc. i now have some little knowledge on how to go about it but since its my first time i need to have some codes similar to my project so that i can get the idea quickly . i am really in need of help because i need to complete the project in time .

     
  91. juicing fast

    April 10, 2014 at 14:21:12

    Howdy, I believe your site could possibly be having web browser compatibility problems.
    When I look at your website in Safari, it looks fine however, when opening in
    IE, it’s got some overlapping issues. I merely wanted to give you a
    quick heads up! Aside from that, fantastic site!

     
  92. rathore

    April 20, 2014 at 03:05:41

    how to send android parameter to the wamp server via php.

     
  93. rasheed

    June 12, 2014 at 13:22:12

    hi,
    I am new to webservices i want to save and retrieve sqlite data through webservices .
    how to do it plz help me

     
  94. Free mobile sex cam chat

    July 21, 2014 at 08:08:53

    Hey there just wanted to give you a quick heads up and let you know a few
    of the images aren’t loading properly. I’m not sure
    why but I think its a linking issue. I’ve tried it in two different web browsers and both show the same outcome.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 1,110 other followers

%d bloggers like this: