Foros del Web » Programación para mayores de 30 ;) » Java »

Conectar a mysql desde android eclipse JSON

Estas en el tema de Conectar a mysql desde android eclipse JSON en el foro de Java en Foros del Web. Hola! Estoy intentando crear una aplicación para android con eclipse que se pueda comunicar con una base de datos mysql. La base de datos está ...
  #1 (permalink)  
Antiguo 21/03/2012, 01:50
 
Fecha de Ingreso: septiembre-2006
Mensajes: 81
Antigüedad: 17 años, 7 meses
Puntos: 0
Conectar a mysql desde android eclipse JSON

Hola!

Estoy intentando crear una aplicación para android con eclipse que se pueda comunicar con una base de datos mysql.
La base de datos está en un hosting donde solo te dejan acceder desde tu servidor y por lo tanto intento ejecutar desde eclipse un script php que tengo en el servidor.
Encontré un tutorial donde me proponían este código usando JSON. Previamente en el script php y una vez efectuada la lectura a la BBDD se ejectuta la instrucción:

print(json_encode($output));

Pero al correr el software de java me salta una excepción NetworkOnMainThread Exception en la siguiente línea
HttpResponse response = httpclient.execute(httppost);

Como puedo solucionarlo????

Muchas gracias

Código:
package com.list;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class city extends ListActivity {

JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

 ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
     HttpResponse response = httpclient.execute(httppost);
     HttpEntity entity = response.getEntity();
     is = entity.getContent();
     }catch(Exception e){
         Log.e("log_tag", "Error in http connection"+e.toString());
    }
//convert response to string
try{
      BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
       sb = new StringBuilder();
       sb.append(reader.readLine() + "\n");

       String line="0";
       while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
        }catch(Exception e){
              Log.e("log_tag", "Error converting result "+e.toString());
        }
//paring data
int ct_id;
String ct_name;
try{
      jArray = new JSONArray(result);
      JSONObject json_data=null;
      for(int i=0;i<jArray.length();i++){
             json_data = jArray.getJSONObject(i);
             ct_id=json_data.getInt("CITY_ID");
             ct_name=json_data.getString("CITY_NAME");
         }
      }
      catch(JSONException e1){
    	  Toast.makeText(getBaseContext(), "No City Found" ,Toast.LENGTH_LONG).show();
      } catch (ParseException e1) {
			e1.printStackTrace();
	}
}
}
    }
  #2 (permalink)  
Antiguo 11/04/2012, 08:41
 
Fecha de Ingreso: enero-2011
Mensajes: 3
Antigüedad: 13 años, 3 meses
Puntos: 0
Respuesta: Conectar a mysql desde android eclipse JSON

Creo que el problema lo tienes en esta línea:

HttpPost httppost = new HttpPost("http://10.0.2.2/city.php");

Le estás pasando la dirección localhost del móvil en lugar de la ruta del servidor:

HttpPost httppost = new HttpPost("http://ruta_servidor_con_myslq/city.php");

Saludos.
  #3 (permalink)  
Antiguo 31/07/2012, 10:07
 
Fecha de Ingreso: julio-2012
Ubicación: Mexico
Mensajes: 2
Antigüedad: 11 años, 9 meses
Puntos: 0
Respuesta: Conectar a mysql desde android eclipse JSON

jgar, quisiera hacer una aplicación que se conecte a una base de datos igual a la que mencionas me podrías ayudar, gracias desde ya..

Etiquetas: android, eclipse, jar, json, mysql, string
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:21.