This article described the way to access JSon data from PHP.
create a database 'Enrichware' and add the 'Emp' table with fields, Name,Dept and Salary. We are going to use PHP code to fetch the data from mysql. The php code will get Dept name as parameter. Then it will run a query in the backend and fetches the result. The result is then converted into JSon and posted. Our Android application gets the JSon data and displays the result.
Create the following file in PHP and deploy it in apache server.
This php code fetches the sales details from emp table. dept is passed as argument and it filters the result.
<?php
mysql_connect("localhost","root","root");
mysql_select_db("Enrichware");
$q=mysql_query("SELECT * FROM Emp WHERE Dept='".$_REQUEST['Dept']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
echo $q;
print(json_encode($output));
mysql_close();
?>
Following Android code calls the PHP file and passes the Dept as parameter. The fetched JSon data is then parsed and result is displayed in a textview.
package com.mysql;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MySQL extends Activity {
Button btnGetData;
TextView txtMessage;
EditText txtDepartment;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMessage = (TextView) findViewById(R.id.txtMessage);
txtDepartment = (EditText) findViewById(R.id.txtDepartment);
btnGetData = (Button) findViewById(R.id.btnGetData);
btnGetData.setOnClickListener((OnClickListener) new clicker());
}
class clicker implements OnClickListener {
@Override
public void onClick(View v) {
InputStream is = null;
String result = "";
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Dept", txtDepartment.getText().toString()));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://<your host here>/employee.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);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
txtMessage.setText(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "Name: " + json_data.getInt("Name")
+ ", Dept: " + json_data.getString("Dept")
+ ", salary: " + json_data.getInt("Salary"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
}
The layout file is here
create a database 'Enrichware' and add the 'Emp' table with fields, Name,Dept and Salary. We are going to use PHP code to fetch the data from mysql. The php code will get Dept name as parameter. Then it will run a query in the backend and fetches the result. The result is then converted into JSon and posted. Our Android application gets the JSon data and displays the result.
Create the following file in PHP and deploy it in apache server.
This php code fetches the sales details from emp table. dept is passed as argument and it filters the result.
<?php
mysql_connect("localhost","root","root");
mysql_select_db("Enrichware");
$q=mysql_query("SELECT * FROM Emp WHERE Dept='".$_REQUEST['Dept']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
echo $q;
print(json_encode($output));
mysql_close();
?>
Following Android code calls the PHP file and passes the Dept as parameter. The fetched JSon data is then parsed and result is displayed in a textview.
package com.mysql;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MySQL extends Activity {
Button btnGetData;
TextView txtMessage;
EditText txtDepartment;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtMessage = (TextView) findViewById(R.id.txtMessage);
txtDepartment = (EditText) findViewById(R.id.txtDepartment);
btnGetData = (Button) findViewById(R.id.btnGetData);
btnGetData.setOnClickListener((OnClickListener) new clicker());
}
class clicker implements OnClickListener {
@Override
public void onClick(View v) {
InputStream is = null;
String result = "";
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Dept", txtDepartment.getText().toString()));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://<your host here>/employee.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);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
txtMessage.setText(result);
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "Name: " + json_data.getInt("Name")
+ ", Dept: " + json_data.getString("Dept")
+ ", salary: " + json_data.getInt("Salary"));
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}
}
The layout file is here
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<Button
android:id="@+id/btnGetData"
android:layout_width="122px"
android:layout_height="wrap_content"
android:text="Get Data"
android:layout_x="94px"
android:layout_y="66px"
>
</Button>
<TextView
android:id="@+id/txtMessage"
android:layout_width="279px"
android:layout_height="289px"
android:text="TextView"
android:layout_x="20px"
android:layout_y="121px"
>
</TextView>
<TextView
android:id="@+id/widget32"
android:layout_width="wrap_content"
android:layout_height="20px"
android:text="Department"
android:layout_x="33px"
android:layout_y="24px"
>
</TextView>
<EditText
android:id="@+id/txtDepartment"
android:layout_width="141px"
android:layout_height="wrap_content"
android:textSize="18sp"
android:layout_x="128px"
android:layout_y="13px"
>
</EditText>
</AbsoluteLayout>
Screenshot




4 comments:
This is a really helpful tutorial, Thanks.
If you are returning more than 1 value, and want to add value 1 to textview1, value 2 to textview2 etc, How would you do that?
really great data thanks for sharing.
cloud computing training in chennai/android training chennai
Useful information. Thanks!. SSISEducation.com is a best training institute offers PHP Training in Chennai. We are providing best training institute for PHP and MySql training courses in Chennai.
Really great application...
Post a Comment