Home Menu

Menu



Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 11/02/15, 02:01:43
Avatar de manolazo
manolazo manolazo no está en línea
Miembro del foro
Mensajes: 219
 
Fecha de registro: jun 2012
Localización: Madrid
Mensajes: 219
Modelo de smartphone: Samsung Galaxy S7 edge
Tu operador: Pepephone
Mencionado: 1 comentarios
Tagged: 0 hilos
Obtener JSON en php para mostrarlo en aplicación.

Buenas

Hace unos dias mire este tutorial http://www.androidhive.info/2012/05/...ith-php-mysql donde indican como conectar android con php y mysql

No tenia ni idea de PHP y me puse un poco con ello instalando WAMP en el pc (apache, mysql y php)

Es una app donde introduces una serie de camposs que se almacenan en una base de datos mysql a traves de PHP en un servidor.

Lo he probado y la app no funciona ni a mi ni a nadie por lo que veo en los comentarios.

El error esta en que is = httpEntity.getContent(); parece que saca todo el contenido del php en html (eso es lo que veo poniendo un log
Log.d("Create lineas", sb.toString());) y cuando intenta convertir json = sb.toString(); da un error ya que sb no es un archivo json sino un string con muchas lineas de codigo html del archivo php


La pregunta es como sacaria el json del php para que se pudiese leer facilmente desde android???

Código:

<?php
 
/*
 * Following code will create a new product row
 * All product details are read from HTTP Post Request
 */
 
$ar = fopen("crear_prod.json","w");
// array for JSON response
$response = array();
 
// check for required fields
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) {
 
    $name = $_POST['name'];
    $price = $_POST['price'];
    $description = $_POST['description'];
 
    // include db connect class
    require_once __DIR__ . '/db_connect.php';
 
    // connecting to db
    $db = new DB_CONNECT();
	
	 
    // mysql inserting a new row
    $result = mysql_query("INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')");
 
    // check if row inserted or not
    if ($result) {
        // successfully inserted into database
        $response["success"] = 1;
        $response["message"] = "Product successfully created.";
 
        // echoing JSON response
        echo json_encode($response);
		
		
    } else {
        // failed to insert row
        $response["success"] = 0;
        $response["message"] = "Oops! An error occurred.";
 
        // echoing JSON response
        echo json_encode($response);
		
    }
} else {
    // required field is missing
    $response["success"] = 0;
    $response["message"] = "Required field(s) is missing";
 
    // echoing JSON response
    echo json_encode($response);
	
}
?>

He pensado en poner en el php
$ar = fopen("crear_prod.json","w");
$jsonvar=json_encode($response);
fwrite($ar, $jsonvar);
fclose($ar);
y asi de esta forma crear un archivo json y luego leerlo pero no se si eso se haria asi.

Aqui el codigo en android:

Código:
	 // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> 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();
            Log.d("Create lineas", sb.toString());
            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;
 
    }
Parece ser que lo mejor en estos casos es usar un servicio REST o SOAP , pero ya es por curiosidad y saber como funciona
Responder Con Cita


  #2  
Viejo 11/02/15, 10:04:56
Avatar de kriogeN
kriogeN kriogeN no está en línea
Colaborador/a
Mensajes: 4,637
Compra y venta: (1)
 
Fecha de registro: oct 2010
Localización: Murcia
Mensajes: 4,637
Modelo de smartphone: Samsung Galaxy S7 Edge SM-G935F
Versión de ROM: CM13 - CM 11
Tu operador: Vodafone
Mencionado: 60 comentarios
Tagged: 3 hilos
Te recomiendo que le eches un vistazo a la librería GSON de Google, te evita todo el trabajo de serializar y deserializar JSON.

https://code.google.com/p/google-gson
Responder Con Cita
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android


Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 05:16:19 (GMT +2)

Cookies
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007