PDA

Ver la Versión Completa : Obtener JSON en php para mostrarlo en aplicación.


manolazo
11/02/15, 02:01:43
Buenas

Hace unos dias mire este tutorial http://www.androidhive.info/2012/05/how-to-connect-android-with-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???




<?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:


// 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

kriogeN
11/02/15, 10:04:56
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/