Hola a todos-!
Tengo el siguiente Script php .
Código PHP:
<?php
$frutas = array();
$posts["naranjas"] = "2";
$posts["manzanas"] = "10";
$posts["bananas"] = "12";
$posts["peras"] = "5";
header('Content-type: application/json');
echo json_encode(array('posts'=>$posts));
?>
pero no puedo recoger el json en mi Activity.
Básicamente lo que quiero realizar es que al presionar un boton me recorra el json , aqui les dejo el codigo de mi java
Hace mas de 5 horas que estoy buscando informacion en google y vi que usan esta linea para parsear el json
JSONObject jsonObj = new JSONObject(sb);
pero si la coloco me da error.
Este metodo seria el Onclick que tiene asociado el boton.
Código Javascript
:
Ver originalpublic void encender(View v){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String parameters = "username=usuarioprueba";
String response = null;
try
{
url = new URL("http://192.168.1.100/holamundo.php");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
response = sb.toString();
isr.close();
reader.close();
// JSONObject jsonObj = new JSONObject(sb);
// HATA ACA LLEGO BIEN Y ME MOSTRO EL JSON !!!!!!!
Toast.makeText(this,response,Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(this,"no entro :(",Toast.LENGTH_SHORT).show();
// error while connecting to the server. please try afetr some time.
}
}
catch(IOException e)
{
Toast.makeText(this,"El error es: "+e,Toast.LENGTH_SHORT).show();
//Error
}
}
Espero que alguien me pueda ayudar
Gracias !!