【问题标题】:android.os.NetworkOnMainThreadException json android [duplicate]android.os.NetworkOnMainThreadException json android [重复]
【发布时间】:2013-05-08 14:42:50
【问题描述】:

在下面的代码中,我在运行我的 android 项目以将 json 从第二个布局发送到 cloudant.com 时出错, quiero mandar json desde android en un segundo layout pero me manda el error android.os.NetworkOnMainThreadException desde el logcat

    //Obtenemos una referencia al LocationManager
    locManager = 
        (LocationManager)getSystemService(Context.LOCATION_SERVICE);
    //Obtenemos la última posición conocida
    final Location loc = 
        locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);



    // buton ejecuta
    btnActualizar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        //  comenzarLocalizacion();



            HttpPost request = new HttpPost( "https://tonatiuhnava.cloudant.com/android/" );
            request.addHeader( "Content-Type", "application/json" );
            request.addHeader( "Authorization", "Basic " + Base64.encodeToString( "tonatiuhnava:70n471uh".getBytes(), Base64.NO_WRAP));
            JSONObject cadena = new JSONObject();

            if(loc != null)
            {

            try{
                cadena.put("nombre", "tonatiuhNava");//Le asignamos los datos que necesitemos
                cadena.put("Category", new Integer(01));
                cadena.put("Event", new Integer(201));

                cadena.put("Fecha",curTime);
                //cadena.put("Fecha",  currentDate.toGMTString());
                cadena.put("longitud", new Double(loc.getLongitude())); 
                cadena.put("Latitud", new Double(loc.getLatitude()));

            } catch ( JSONException e )
            {
                Log.d( "WAZAAA" , "error json" );

            }

            try{
                request.setEntity( new StringEntity(  cadena.toString() ) );

            } catch ( Exception e ){
                Log.d( "WAZAAA" , "error entity" );

            }

            DefaultHttpClient connection = new DefaultHttpClient();
            try{
          Log.d( "WAZAAA" , "haciendo request");

            HttpResponse execute = connection.execute( request );
            Log.d( "WAZAAA" , "request hecho");

            byte[] bytes = new byte[1000];
            int numRead = 0;
            StringBuilder x = new StringBuilder();
            InputStream stream = execute.getEntity().getContent();
            stream.read( bytes );
            x.append( new String( bytes, 0, numRead ) );



            Log.d( "WAZAAA" , execute.getStatusLine().getReasonPhrase() );
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                Log.e( "WAZAAA" , "client error" );
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.e( "Internet Please :..(" , "IO error" );
            }
            Log.d( "WAZAAA" , "fin");

            // termina if 
            }else {
                Context context = getApplicationContext();
                CharSequence text = "Espere a que cargue coordenadas...";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();


            }

        }

【问题讨论】:

    标签: android json


    【解决方案1】:

    阻塞请求不能在 UI 线程上运行,它们应该在单独的线程上运行。使用 AsyncTask。阅读this

    【讨论】:

    • 异步任务?一个例子?
    猜你喜欢
    • 1970-01-01
    • 2013-10-16
    • 2013-05-02
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 2012-03-13
    • 2013-08-20
    相关资源
    最近更新 更多