Communication application Android et MySQL
Bonjour tout le monde,
Je me suis lancé dans la programmation android et après quelques lectures de tutos (http://www.enis-android-club.com/), j'ai décidé de faire un petit projet qui me liste les données d'une table (telephone avec les attributs id,Designation,Detail) que j'ai crée sous mysql.
Voici les fichiers de codes que j'ai écris:
- connexion.php
- affichage_telephone.php
- une classe ServiceHandler.java que j'ai pris à l'adresse http://pastebin.com/4VsfVvCA.
- mon MainActivity.java
connexion.php
Code:
1 2 3 4 5
|
<?php
mysql_connect('localhost','root','');
mysql_select_db('bdtigo');
?> |
affichage_telephone.php
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
<?php
// La table de réponse JSON
$response = array();
// connexion à la base
include 'connexion.php';
// recupérer les données de la table téléphone
$result = mysql_query("select * from telephone") or die(mysql_error());
// tester si on a recu des données ou non
if (mysql_num_rows($result) > 0) {
// Ajouter les valeurs à la liste
$response["valeurs"] = array();
while ($row = mysql_fetch_array($result)) {
$ligne = array();
$ligne["id"] = $row["id"];
$ligne["Designation"] = $row["Designation"];
$ligne["Detail"] = $row["Detail"];
array_push($response["valeurs"], $ligne);
}
// cuccès
$response["success"] = 1;
$response["message"] = "Les donnees sont bien recuperees";
// encoder la réponse
echo json_encode($response);
} else {
// on a rien trouvé
$response["success"] = 0;
$response["message"] = "Aucun telephone dans la base";
echo json_encode($response);
}
?> |
ServiceHandler.java
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
|
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {}
/*
* Making service call
* @url - url to make request
* @method - http request method
* */
public String ServiceCall(String url, int method) {
return this.ServiceCall(url, method, null);
}
/*
* Making service call
* @url - url to make request
* @method - http request method
* @params - http request params
* */
public String ServiceCall(String url, int method, List<NameValuePair> params) {
try {
// Client http
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Choisir mode requête http
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// ajouter les paramètres post
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
} |
MainActivity.java
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
|
public class MainActivity extends ActionBarActivity{
String urlGet = "http://10.0.2.2:82/AndroidWork/affichage_telephone.php";
GetDataAsyncTask getData;
String message;
int success;
ListView lv;
List<String> maListDonnee;
ArrayAdapter arrayadp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listviewperso);
maListDonnee = new ArrayList<>();
getData = new GetDataAsyncTask();
getData.execute();
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
Log.i("add", "onPreExecute");
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params) {
Log.i("add", " start doInBackground");
ServiceHandler sh = new ServiceHandler();
// Envoyer une requête sur l'url
String jsonStr = sh.ServiceCall(urlGet, ServiceHandler.POST);
Log.d("Response: ", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// retourner valeur succèss
success = jsonObj.getInt("success");
Log.i("success", String.valueOf(success));
if (success == 0) {
// success=0 ==> On a un String = message
message = jsonObj.getString("message");
Log.i("message", message);
} else if (success == 1) {
// success=1 ==> On a un tableau des données = valeurs
JSONArray dataValues = jsonObj.getJSONArray("valeurs");
// Parcourir
for (int j = 0; j < dataValues.length(); j++) {
JSONObject values = dataValues.getJSONObject(j);
// returner la valeur de la colonne id dans valCol1...
String valCol1 = values.getString("id");
String valCol2 = values.getString("Designation");
String valCol3 = values.getString("Detail");
maListDonnee.add(valCol2);
Log.i("Row " + (j + 1), valCol2);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Aucune donnee a cette adresse");
}
Log.i("add", " end doInBackground");
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i("add", "onPostExecute");
super.onPostExecute(result);
if (success == 1) {
Toast.makeText(getApplicationContext(), "Bien recue ", Toast.LENGTH_LONG).show();
arrayadp = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, maListDonnee);
lv.setAdapter(arrayadp);
} else {
Toast.makeText(getApplicationContext(), "Erreur", Toast.LENGTH_LONG).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
J'ai rien comme erreur à l'exécution mais ça m'affiche pas de données, ma variable jsonStr ne recupère rien à l'adresse spécifiée.
J'ai besoin d'aide pour comprendre c'est quoi le problème.
Cordialement.