Connettere una APP Android ad un database mysql remoto
Una delle soluzioni più semplici ed utilizzate e quelle di costruire un "service in the middle". In pratica un servizio che si ponga nel mezzo e si occupi di serializzare/deserializzare i dati sa caricare/scaricare.
Ipotizziamo di avere sul server MYSQL remoto la seguente tabella:
CREATE TABLE `people` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 100 ) NOT NULL ,
`sex` BOOL NOT NULL DEFAULT '1',
`birthyear` INT NOT NULL
)
In PHP potremmo serializzare i risultati di una query nel formato JSON in questo modo:
-
<?php
-
mysql_connect("host","username","password");
-
mysql_select_db("PeopleData");
-
-
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
-
while($e=mysql_fetch_assoc($q))
-
$output[]=$e;
-
-
print(json_encode($output));
-
-
mysql_close();
-
?>
Maggiori informazioni sul formato JSON qui: http://it.wikipedia.org/wiki/JSON
Il passo successivo sarà quello di lavorare ( ad esempio ) con i dati "serializzati" JSON nel modo seguente:
-
String result = "";
-
//the year data to send
-
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
-
nameValuePairs.add(new BasicNameValuePair("year","1980"));
-
-
//http post
-
try{
-
HttpClient httpclient = new DefaultHttpClient();
-
HttpPost httppost = new HttpPost("http://example.com/getAl
lPeopleBornAfter.php"); -
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
-
HttpResponse response = httpclient.execute(httppost);
-
HttpEntity entity = response.getEntity();
-
InputStream 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(newInputStreamReader(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);
-
for(int i=0;i<jArray.length();i++){
-
JSONObject json_data = jArray.getJSONObject(i);
-
Log.i("log_tag","id: "+json_data.getInt("id")+
-
", name: "+json_data.getString("name")+
-
", sex: "+json_data.getInt("sex")+
-
", birthyear: "+json_data.getInt("birthyear")
-
);
-
}
-
}
-
}catch(JSONException e){
-
Log.e("log_tag", "Error parsing data "+e.toString());
-
}
Ovviamente se si vuole gestire la connessione in HTTPS la cosa è fattibile.










