Tuto Android : Peupler un Spinner à partir d'une base Mysql à l'aide de web Service REST (php, json)



Peupler un Spinner à partir d'une base Mysql à l'aide de web Service REST (php, json)

Dans un précédent tutoriel nous avons appris à insérer des données dans une base distante à travers une application android. Dans ce tuto on va apprendre à peupler un Spinner à partir d'une base Mysql externe.
Tout d'abord nous devons avoir un logiciel qui contient un serveur web apache et un SGBD mysql. Parmi ces applications on trouve :

  • WAMP 
  • ou EasyPHP. 
  • Ou vous pouvez tout simplement utiliser un serveur distant.

La première étape consiste à créer sa base de données. Dans notre cas notre base s'appelle culture qui contient une table qui s'appelle plante.


CREATE TABLE `plante` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nom` varchar(30) COLLATE latin1_general_ci NOT NULL,
  `nature` varchar(30) COLLATE latin1_general_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 COLLATE=latin1_general_ci AUTO_INCREMENT=12 ;

Par la suite nous devons créer un web services de type REST . 

Ce web service se fait à base de php et sera héberger dans un serveur web apache. Le résultat de ce web service  doit être sous format json.
Tout d'abord nous devons créer un fichier php qui permet de se connecter au serveur de la base de données et pour sélectionner la base qui contient notre table. Ce fichier sera par la suite invoqué par notre web service par la suite.

Ce fichier s'appelle connexion.php
<?php
//en cas ou vous utiliser EasyPHP le nom de serveur est 127.0.0.1
//en cas ou vous utiliser EasyPHP le nom d'utilisateur  est root
//en cas ou vous utiliser EasyPHP comme mot de passe il faut mettre "".
$connexion =mysql_connect("nom de serveur de la base","nom d'utilisateur de base ","mot de passe de l'utilisateur");
if (!$connexion ){
die("connexion echoué :".mysqli_error());
}
//selectionner la table, dans notre cas la table s'appelle plante
$db_select=mysql_select_db("plante");
if(!$db_select){
die("selection de base echoué:".mysqli_error());
}
?>


Il reste maintenant de développer notre web service,on l'appelle all.php
<?php
require_once('connexion.php');
$response = array();
$result = mysql_query("SELECT *FROM plante") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) 
{
$response["plante"] = array();
while ($row = mysql_fetch_array($result)) 
{
// temp user array
$product = array();
$product["id"] = $row["id"];
$product["nom"] = $row["nom"];
$product["nature"] = $row["nature"];
// push single product into final response array
array_push($response["plante"], $product);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
}
 else
 {// no products found
$response["success"] = 0;
$response["message"] = "No products found";
// echo no users JSON
echo json_encode($response);
}?>

On va passer maintenant pour développer notre application android. Tout d'abord il faut ajouter la permision internet dans notre fichier manifest.xml.

<uses-permission android:name="android.permission.INTERNET" />

Si le build tools version et le compile sdk version sont égales ou supérieurs à la version 23, dans ce cas la vous devez ajouter la ligne suivante dans le fichier build.gradle(Module: app).

useLibrary 'org.apache.http.legacy'

Vient maintenant le temps pour créer notre interface graphique. On l'appelle activityspinner.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.asus.parser.SpinnerActivity">

    <Spinner
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/spinner"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show"
        android:id="@+id/button4"
        android:layout_below="@+id/spinner"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

On passe maintenant à la partie java. 

Tout d'abord nous devons créer une classe dans laquelle nous créons une méthode permettant de communiquer avec notre web service. 
On l'appelle JSONParser.java
public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
                                      List params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

Il reste maintenant de créer notre Activité, on l'appelle SpinnerActivity.java
public class SpinnerActivity extends Activity implements AdapterView.OnItemSelectedListener{
Spinner s;
    Button b;
    ProgressDialog pDialog;
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();

    // url to get all products list
    private static String url = "http://....../all.php";
    // products JSONArray
    JSONArray products = null;
    ArrayList productsList;
    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PRODUCTS = "plante";

    private static final String TAG_NAME = "nom";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activityspinner);
        s= (Spinner) findViewById(R.id.spinner);
       // b=(Button)findViewById(R.id.button4);
        productsList = new ArrayList< String>();
        s.setOnItemSelectedListener(this);
        new Load().execute();
    }

    @Override
    public void onItemSelected(AdapterView parent, View view, int position, long id)
    {

    }

    @Override
    public void onNothingSelected(AdapterView parent)
    {

    }

    class Load extends AsyncTask {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            pDialog = new ProgressDialog(SpinnerActivity.this);
            pDialog.setMessage("Loading...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        /**
         * getting All products from url
         * */
        protected String doInBackground(String... args) {
            // Building Parameters
            List params = new ArrayList();
            // getting JSON string from URL
            JSONObject json = jParser.makeHttpRequest(url, "GET", params);

            // Check your log cat for JSON reponse
            Log.d("All Products: ", json.toString());


            // Checking for SUCCESS TAG
            int success = 0;
            try {
                success = json.getInt(TAG_SUCCESS);
                if (success == 1) {
                    // products found
                    // Getting Array of Products
                    products = json.getJSONArray(TAG_PRODUCTS);

                    // looping through All Products
                    for (int i = 0; i < products.length(); i++) {
                        JSONObject c = products.getJSONObject(i);

                        // Storing each json item in variable

                        String name = c.getString(TAG_NAME);


                        // adding name to ArrayList
                        productsList.add(name);
                    }
                } else {
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }



            return null;
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        protected void onPostExecute(String file_url) {

            pDialog.dismiss();
            // Creating adapter for spinner
            ArrayAdapter adapter = new ArrayAdapter(SpinnerActivity.this,
                    android.R.layout.simple_spinner_item, productsList);

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            s.setAdapter(adapter);
        }

    }
}

Commentaires

Posts les plus consultés de ce blog

Ionic 2 : Envoie d'une image vers un serveur web à l'aide de PHP et Angular 2

Premier tutoriel avec Arduino et Proteus ISIS

Login et password ,formulaire d'authentification sous android avec mysql et json