dilux
05/12/14, 12:03:18
Hola buenas tengo una base de datos mysql y ya se como realizar una consulta fija con httget y que me muestre los datos ( nombre y una imagen) en un listview, pero ahora necesito llenar ese listview con una consuta where segun pongan en un edittext. mi codigo es este;
una clase con la conexion al php
public class httpHandler {
public String post(String posturl, String where){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
//AÑADIR PARAMETROS
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data",where));
httppost.setEntity(new UrlEncodedFormEntity(params));
/*Finalmente ejecutamos enviando la info al server*/
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();/*y obtenemos una respuesta*/
String text = EntityUtils.toString(ent);
return text;
}
catch(Exception e) {
e.printStackTrace();
return "error";}
}
}
y aqui un asyntask para httpost:
class AsyncExecute extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
try {
// Llamamos al servicio web para recuperar los datos
httpHandler handler = new httpHandler();
txt = handler.post("http://comupunt.esy.es/nombreb.php", "pedro");
HttpGet httpGet = new HttpGet("http://comupunt.esy.es/nombreb.php");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse)httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
InputStream iStream = buffer.getContent();
String aux = "";
BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
aux += line;
}
// Parseamos la respuesta obtenida del servidor a un objeto JSON
JSONObject jsonObject = new JSONObject(aux);
JSONArray cities = jsonObject.getJSONArray("cities");
// Recorremos el array con los elementos cities
for(int i = 0; i < cities.length(); i++) {
JSONObject city = cities.getJSONObject(i);
// Creamos el objeto City
City c = new City(city.getString("name"),
city.getInt("nametwo"),city.getString("posicion") );
c.setData(city.getString("photo"));
listaPersonas.add(c.photo);
// Almacenamos el objeto en el array que hemos creado anteriormente
citiesAvaiable.add(c);
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// Creamos el objeto CityAdapter y lo asignamos al ListView
CityAdapter cityAdapter = new CityAdapter(MainActivity.this, citiesAvaiable);
lvCities.setAdapter(cityAdapter);
super.onPostExecute(result);
}
y esta es la consulta en php:
<?php
$con = mysql_connect('mysql.hostinger.es', 'miBD', '*****');
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$dato = $_POST['data'];
$cities['cities'] = array();
if( $con )
{
mysql_select_db('u453215752_droid');
$res = mysql_query('select name, nametwo, photo, posicion from cities where
name='$dato'');
while( $row = mysql_fetch_array($res) ) {
array_push($cities['cities'], array('posicion' => $row['posicion'], 'name' =>
$row['name'], 'nametwo' => $row['nametwo'], 'photo' => base64_encode($row['photo'])));
}
mysql_free_result($res);
mysql_close($con);
}
header('Content-type: application/json');
echo json_encode($cities);
luego ejecuto el asyntask en un button click pero el listview se queda vacio, que estoy haciendo mal, gracias!
una clase con la conexion al php
public class httpHandler {
public String post(String posturl, String where){
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(posturl);
//AÑADIR PARAMETROS
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("data",where));
httppost.setEntity(new UrlEncodedFormEntity(params));
/*Finalmente ejecutamos enviando la info al server*/
HttpResponse resp = httpclient.execute(httppost);
HttpEntity ent = resp.getEntity();/*y obtenemos una respuesta*/
String text = EntityUtils.toString(ent);
return text;
}
catch(Exception e) {
e.printStackTrace();
return "error";}
}
}
y aqui un asyntask para httpost:
class AsyncExecute extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
try {
// Llamamos al servicio web para recuperar los datos
httpHandler handler = new httpHandler();
txt = handler.post("http://comupunt.esy.es/nombreb.php", "pedro");
HttpGet httpGet = new HttpGet("http://comupunt.esy.es/nombreb.php");
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = (HttpResponse)httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
BufferedHttpEntity buffer = new BufferedHttpEntity(entity);
InputStream iStream = buffer.getContent();
String aux = "";
BufferedReader r = new BufferedReader(new InputStreamReader(iStream));
StringBuilder total = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
aux += line;
}
// Parseamos la respuesta obtenida del servidor a un objeto JSON
JSONObject jsonObject = new JSONObject(aux);
JSONArray cities = jsonObject.getJSONArray("cities");
// Recorremos el array con los elementos cities
for(int i = 0; i < cities.length(); i++) {
JSONObject city = cities.getJSONObject(i);
// Creamos el objeto City
City c = new City(city.getString("name"),
city.getInt("nametwo"),city.getString("posicion") );
c.setData(city.getString("photo"));
listaPersonas.add(c.photo);
// Almacenamos el objeto en el array que hemos creado anteriormente
citiesAvaiable.add(c);
}
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result) {
// Creamos el objeto CityAdapter y lo asignamos al ListView
CityAdapter cityAdapter = new CityAdapter(MainActivity.this, citiesAvaiable);
lvCities.setAdapter(cityAdapter);
super.onPostExecute(result);
}
y esta es la consulta en php:
<?php
$con = mysql_connect('mysql.hostinger.es', 'miBD', '*****');
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$dato = $_POST['data'];
$cities['cities'] = array();
if( $con )
{
mysql_select_db('u453215752_droid');
$res = mysql_query('select name, nametwo, photo, posicion from cities where
name='$dato'');
while( $row = mysql_fetch_array($res) ) {
array_push($cities['cities'], array('posicion' => $row['posicion'], 'name' =>
$row['name'], 'nametwo' => $row['nametwo'], 'photo' => base64_encode($row['photo'])));
}
mysql_free_result($res);
mysql_close($con);
}
header('Content-type: application/json');
echo json_encode($cities);
luego ejecuto el asyntask en un button click pero el listview se queda vacio, que estoy haciendo mal, gracias!