sql >> Base de Datos >  >> RDS >> Mysql

Android:la consulta JSON mySQL da NetworkOnMainThreadException

Escuché que a partir de ICS, no está permitido realizar operaciones de red en el subproceso de la interfaz de usuario (principal). Por lo tanto, debe realizar esta operación en un hilo separado. Así que usa AsyncTask , Conversación o HandlerThread con Looper y Handler para realizar la operación web. Si lo prueba en un dispositivo que ejecuta froyo o gingerbread, estaría bien, pero no en ICS.

Con respecto a su intento de ejecutarlo a través del controlador o AsyncTask, depende de cómo lo haya hecho. Pegue ese código para ver el problema.

Actualizar

public class MySQLAndroidActivity extends ListActivity {

    private static final String url = "http://X.X.X.X/test.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2);

        LoadTask t = new LoadTask();
        t.execute(null);

    }

    private static class LoadTask extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {

        }

        @Override
        protected Void doInBackground(Void... params) {
            doStuff();

            return null;
        }
    }





    public static void doStuff() {
        JSONArray jArray;
        String result = null;
        InputStream is = null;
        StringBuilder sb = null;
        HttpResponse response;
        HttpEntity entity;

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);

            entity = response.getEntity();

            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
            System.exit(1);
        }

        // 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;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            is.close();
            result = sb.toString();

            Log.i("json string", result);
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }


        // parsing data
        String idfriend;
        String id1;
        String id2;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;

            System.out.println("Length " + jArray.length());
            Log.d("DB", "Length " + jArray.length());

            for (int i = 0; i < jArray.length(); i++) {

                System.out.println("counter " + i);
                json_data = jArray.getJSONObject(i);
                idfriend = json_data.getString("idfriend");
                id1 = json_data.getString("id1");
                id2 = json_data.getString("id2");

                System.out.println("id1: " + id1);
            }
        } catch (JSONException e1) {
            Log.d("DB", "Error somewhere");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }

}

*Hubo algunos problemas con las llamadas a métodos y el más importante fue que estaba obteniendo claves de JSONObject como Idfriend, Id1, Id2 lo cual está mal porque en tu cadena json las claves son como idfriend, id1, id2 . Se distingue entre mayúsculas y minúsculas, por eso se bloqueaba.