Introduction
You are creating an Android app and want to read data from a MySQL
database and send data. We will create a Web Service in PHP, read from
the MySQL database,
and let the Android connect with the Web Service and send data, and the
Web Service will save it and another Web Service will read data from
MySQL and send it to the Android app.
Using the code
First we have to create the Web service to read data from the MySQL database.
<?php
<pre>
<pre>if(isset($_GET['user']) && intval($_GET['user'])) {
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; $user_id = intval($_GET['user']);
$link = mysql_connect('localhost','root','123456') or die('Cannot connect to the DB');
mysql_select_db('TEST',$link) or die('Cannot select the DB');
$query = "SELECT * FROM `test`.`users`;";
$result = mysql_query($query,$link) or die('Errant query: '.$query);
$posts = array();
if(mysql_num_rows($result)) {
while($post = mysql_fetch_assoc($result)) {
$posts[] = array('post'=>$post);
}
}
if($format == 'json') {
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
}
else {
header('Content-type: text/xml');
echo '';
foreach($posts as $index => $post) {
if(is_array($post)) {
foreach($post as $key => $value) {
echo '<',$key,'>';
if(is_array($value)) {
foreach($value as $tag => $val) {
echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
}
}
echo '</',$key,'>';
}
}
}
echo '';
}
@mysql_close($link);
}
?>
Here is the code for the Android activity to read from the Web Service and parse the JSON object:
public void clickbutton(View v) {
try {
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpParams p = new BasicHttpParams();
p.setParameter("user", "1");
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://10.0.2.2:8080/sample1/" +
"webservice1.php?user=1&format=json";
HttpPost httppost = new HttpPost(url);
try {
Log.i(getClass().getSimpleName(), "send task - start");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(
2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
JSONObject json = new JSONObject(responseBody);
JSONArray jArray = json.getJSONArray("posts");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String s = e.getString("post");
JSONObject jObject = new JSONObject(s);
map.put("idusers", jObject.getString("idusers"));
map.put("UserName", jObject.getString("UserName"));
map.put("FullName", jObject.getString("FullName"));
mylist.add(map);
}
Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
Here is the PHP code to send data to the Web Service and save it:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
$con = mysql_connect('localhost','root','123456')
or die('Cannot connect to the DB');
mysql_select_db('TEST',$con);
mysql_query("INSERT INTO `test`.`users` (UserName, FullName)
VALUES ('".$obj->{'UserName'}."', '".$obj->{'FullName'}."')");
mysql_close($con);
$posts = array(1);
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
Android activity to send data to the Web Service as a JSON object to save in the MySQL database:
public void clickbuttonRecieve(View v) {
try {
JSONObject json = new JSONObject();
json.put("UserName", "test2");
json.put("FullName", "1234567");
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams,
TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
String url = "http://10.0.2.2:8080/sample1/webservice2.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
Toast.makeText(this, result,
Toast.LENGTH_LONG).show();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
}
No comments:
Post a Comment