martes, 17 de enero de 2017

OBTENER DATOS CON ANDROID, PHP Y MYSQL


Para el caso de obtener datos desde una base de datos MySql mediante Android usando Php, el proceso seria el siguiente.


Creamos una nueva clase llamada HttpHandler.

HttpHandler:

package com.mapaes.andresescobar.mapas1;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


public class HttpHandler {

    private static final String TAG = HttpHandler.class.getSimpleName();

    public HttpHandler() {
    }

    public String makeServiceCall(String reqUrl) {
        String response = null;
        try {
            URL url = new URL(reqUrl);
  HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            // read the response            
InputStream in = new BufferedInputStream(conn.getInputStream());
            response = convertStreamToString(in);
        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException: " + e.getMessage());
        } catch (ProtocolException e) {
            Log.e(TAG, "ProtocolException: " + e.getMessage());
        } catch (IOException e) {
            Log.e(TAG, "IOException: " + e.getMessage());
        } catch (Exception e) {
            Log.e(TAG, "Exception: " + e.getMessage());
        }
        return response;
    }

    private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
Para utilizar esta clase y llamarla desde nuesra Activity principal,lo haremos de la siguiente manera:


HttpHandler sh = new HttpHandler();

// Making a request to url and getting responseString 
//URL -> NUESTRA URL http://www.xxxx.com/nuestrophp.php
jsonStr = sh.makeServiceCall(url);
ArrayList<String> listado = new ArrayList<String>();
Log.i(TAG, "Response from url: " + jsonStr);

if (jsonStr != null) {
    try {
        JSONArray jsonarray = new JSONArray(jsonStr);
      
        String texto = null;
        for (int i = 0; i < jsonarray.length(); i++) {
           // JSONObject c = contacts.getJSONObject(i);           
          JSONObject c = jsonarray.getJSONObject(i);


            String id = c.getString("usuario");
            Log.e(TAG, "usuario: " + id);
            String name = c.getString("password");
            Log.e(TAG, "password: " + name);

            texto = c.getString("usuario") + ":" +
                    c.getString("password");
            listado.add(texto);
              }

        Log.e(TAG, "listado: " +listado);
    } catch (final JSONException e) {
        Log.e(TAG, "Json parsing error: " + e.getMessage());


    }




}else {
    Log.e(TAG, "Couldn't get json from server.");


}



Archivo PHP al que se conecta  mediante android por medio de una url y este realiza el volcado de datos desde la base MySql.


nuestrophp.php


<?php
error_reporting(E_ALL ^ E_DEPRECATED);
 $con = mysql_connect("127.0.0.1","usuarioBD","passwordBD") or die ("Sin Conexcion");
 mysql_select_db("nombreBD");
 $sql="select usuario,password from personas";
 $datos=array();
//mysqli_query($link, 'CREATE TEMPORARY TABLE `table`');
 $rs=mysql_query($sql,$con);
 while($row=mysql_fetch_object($rs)){
  $datos[]=$row;
 }
 echo json_encode($datos);
?>

No hay comentarios:

Publicar un comentario