llenar spinner en android desde una base de datos MySQL

Buenas hoy les traigo un nuevo tutorial, veremos como llenar un spinner en android desde una base de datos en Mysqli
bien las recomendaciones acostumbradas de siempre, lean de principio a final y tendrán ceros errores.

Que necesitamos para llenar nuestro spinner?
-paciencia
-un base de datos en mysql
-una web services en php y json
-una aplicación android

Bien empezamos por la base de datos se llamara, spinner y contendrá lo siguiente.

CREATE TABLE IF NOT EXISTS `frutas` (
  `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `nombre` varchar(90) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id` (`id`)
);
INSERT INTO `frutas` (`id`, `nombre`) VALUES
(48, 'manzana'),
(49, 'uva'),
(50, 'papaya'),
(51, 'mango');

Bueno ahora seguimos con nuestra webservice, tendrá la siguiente estructura.

 

crearemos primero la conexion.php

<?php 
$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password="12345"; // Mysql password 
$db_name="frutas"; // Database name 
?>

Ahora nuestro listar.php

<?php
include_once './conexion.php';
$respuesta = array();
$respuesta["frutas"] = array();

// Conectarse al servidor y seleccionar base de datos.
$con = mysqli_connect("$host", "$username", "$password")or die("cannot connect server ");
mysqli_select_db($con,"$db_name")or die("cannot select DB");
$sql="SELECT * FROM frutas";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)){
// Array temporal para crear una sola categoría
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["nombre"] = $row["nombre"];

// Push categoría a final json array
array_push($respuesta["frutas"], $tmp);
}

// Mantener el encabezado de respuesta a json
header('Content-Type: application/json');

//Escuchando el resultado de json
echo json_encode($respuesta);
?>

Ahora nuestro agregar.php

<?php 
include_once './conexion.php';
if (isset($_POST["nombre"]) && $_POST["nombre"] != "") {
// variable respuesta array para json
$respuesta = array();
$nombre = $_POST["nombre"];

$con = mysqli_connect("$host", "$username", "$password")or die("cannot connect server ");
mysqli_select_db($con,"$db_name")or die("cannot select DB");

// mysql query
$query = "INSERT INTO frutas(nombre) VALUES(
'$nombre')";
$result = mysqli_query($con,$query) or die(mysqli_error());
if ($result) {
$respuesta["error"] = false;
$respuesta["message"] = "nueva fruta creado con 
exito!";
} else {
$respuesta["error"] = true;
$respuesta["message"] = "Creacion de nueva fruta 
fallida!";
}
} else {
$respuesta["error"] = true;
$respuesta["message"] = "Nombre de la fruta no se 
encuentra!";
}

// echo json respuesta
echo json_encode($respuesta);
?>

Bien ya tenemos nuestra base de datos y nuestra webservices.
En nuestra aplicacion tendremos 3 archivos.java

Frutas.java
MainActivity.java
ServiceHandler.java

 

Frutas.java

/**
 * Created by androidmorefast on 26/05/2016.
 */
public class Frutas {
    private int id;
    private String name;

    public Frutas(){}

    public Frutas(int id, String name){
        this.setId(id);
        this.setName(name);
    }


    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

MainActivity.java

public class MainActivity extends Activity implements AdapterView.OnItemSelectedListener {

    private Button btnAgregar;
    private TextView txtAgregar;
    private Spinner spinnerfruta;
    // array para listar las frutas
    private ArrayList<Frutas> frutasList;
    ProgressDialog pDialog;

    // API urls
    // Url creacion de nuevas frutas
    private String URL_NEW_FRUTA = "http://192.168.1.33:8080/blog/spinner/agregar.php";
    // Url listar las frutas
    private String URL_LISTA_FRUTA = "http://192.168.1.33:8080/blog/spinner/listar.php";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnAgregar = (Button) findViewById(R.id.btnNuevaFruta);
        spinnerfruta = (Spinner) findViewById(R.id.spinfruta);
        txtAgregar = (TextView) findViewById(R.id.txtFruta);

        frutasList = new ArrayList<Frutas>();

        // seleccionar las frutas del spinner
        spinnerfruta.setOnItemSelectedListener(this);

        btnAgregar.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (txtAgregar.getText().toString().trim().length() > 0) {


                    String nuevaFruta = txtAgregar.getText().toString();


                    new AddNuevafruta().execute(nuevaFruta);
                } else {
                    Toast.makeText(getApplicationContext(),
                            "por favor ingrese nombre de la fruta", Toast.LENGTH_SHORT)
                            .show();
                }
            }
        });

        new Getfrutas().execute();



    }


    private void populateSpinner() {
        List<String> lables = new ArrayList<String>();

        txtAgregar.setText("");

        for (int i = 0; i < frutasList.size(); i++) {
            lables.add(frutasList.get(i).getName());
        }


        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, lables);


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


       spinnerfruta.setAdapter(spinnerAdapter);



    }


    private class Getfrutas extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Obtencion de las frutas..");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            ServiceHandler jsonParser = new ServiceHandler();
            String json = jsonParser.makeServiceCall(URL_LISTA_FRUTA, ServiceHandler.GET);

            Log.e("Response: ", "> " + json);

            if (json != null) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    if (jsonObj != null) {
                        JSONArray frutas = jsonObj
                                .getJSONArray("frutas");

                        for (int i = 0; i < frutas.length(); i++) {
                            JSONObject catObj = (JSONObject) frutas.get(i);
                            Frutas cat = new Frutas(catObj.getInt("id"),
                                    catObj.getString("nombre"));
                            frutasList.add(cat);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                Log.e("JSON Data", "¿No ha recibido ningún dato desde el servidor!");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (pDialog.isShowing())
                pDialog.dismiss();
           populateSpinner();
        }

    }



    private class AddNuevafruta extends AsyncTask<String, Void, Void> {

        boolean nuevaFrutaCreada = false;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("creación de la nueva fruta..");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(String... arg) {

            String newFruta = arg[0];


            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("nombre", newFruta));

            ServiceHandler serviceClient = new ServiceHandler();

            String json = serviceClient.makeServiceCall(URL_NEW_FRUTA,
                    ServiceHandler.POST, params);

            Log.d("Create Response: ", "> " + json);

            if (json != null) {
                try {
                    JSONObject jsonObj = new JSONObject(json);
                    boolean error = jsonObj.getBoolean("error");

                    if (!error) {

                        nuevaFrutaCreada = true;
                    } else {
                        Log.e("Error en la creacion: ", "> " + jsonObj.getString("message"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                Log.e("JSON Data", "No ha recibido ningún dato desde el servidor!");
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (pDialog.isShowing())
                pDialog.dismiss();
            if (nuevaFrutaCreada) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        new Getfrutas().execute();
                        frutasList.clear();
                    }
                });
            }
        }
    }


    public void onItemSelected(AdapterView<?> parent, View view, int position,
                               long id) {
        Toast.makeText(
                getApplicationContext(),
                parent.getItemAtPosition(position).toString() + " Seleccionado" ,
                Toast.LENGTH_LONG).show();

    }


    public void onNothingSelected(AdapterView<?> arg0) {
    }
}

ServiceHandler.java

public class ServiceHandler {

    static InputStream is = null;
    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 makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /*
     * Making service call
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     * */
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            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, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            response = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error: " + e.toString());
        }

        return response;

    }
}

 

Como de costumbre les dejare el archivo del código android, todo esta documentado, si tienen dudas al respecto me dejan un comentario.

13 comentarios en «llenar spinner en android desde una base de datos MySQL»

  1. Alvaro Lopez

    Hola, he probado tu codigo y funciona super bien, ahora bien quiero hacer algo parecido con otra BD y otro servidor,
    He copiado el archivo ServiceHandler.java a mi aplicacion y me da multitud de errores,

    * */
    public String makeServiceCall(String url, int method,
    List params) {

    *** NameValuePair me da el error Cannot resolve simbol NameValuePair

    y como este mucho otros

    try {
    // http client
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpEntity httpEntity = null;
    HttpResponse httpResponse = null;

  2. Anónimo

    hola que tal.. me podrias ayudar con esto…lo que pasa que me sale un error q dice q no puede convertir JSONObject a JSONArray… este es mi codigo….
    JSONObject jsonObject = new JSONObject(json);
    if (jsonObject != null) {
    JSONArray provincias = jsonObject.getJSONArray("provincias"); // o probar con el nombre de la tabla

    for (int i = 0; i < provincias.length(); i++) {
    JSONObject catObj = provincias.getJSONObject(i);
    Provincia cat = new Provincia(catObj.getString("prov_nombre"));
    lstProvincias.add(cat);
    }

    de antemano muchas gracias espero tu respuesta 🙂

  3. MYSPACE ALCALA

    hola, una duda grande, hice el proceso con otro spinner en la misma aplicacion y no me funciona, repeti todo pero con otra clase,, digamos frutasverdes, se detiene mi aplicacion y no inicia, sabes cual seria el problema.
    gracias

  4. Neomar Blanco

    Buenas tardes, segui el tutorial y lo adapte a mi servidor y base de datos y despues de tanto pude conseguirlo sin problemas.. Ahora el detalle es que mi aplicación tiene 5 spinner diferente, y me gustaria aplicar este metodo para todos…

    Ya cree la tabla para cada spinner en mi BD.. Ya probe el código individual y funciona, pero al copiar el codigo en mi proyecto principal me genera conflicto y la aplicación se cuelga…

    Me gustaria saber como modifico el codigo para alimentar 2 spinner diferentes dentro de la misma aplicación

    De antemano muchas gracias

  5. Pingback: Como llenar un spinner con volley y mysql en android | ANDROFAST

Deja una respuesta

Tu dirección de correo electrónico no será publicada.

WhatsApp chat