3

Quiero enviar información de un formulario a mi base de datos para crear un login. Sin embargo, no se envían los datos y tampoco origina error. ¿Me podrían colaborar?

public class Main2Activity extends AppCompatActivity {

Button botonRegistrarse;
EditText TextoNombres, TextoApellidos, TextoCedula, TextoTelefono1, TextoTelefono2, TextoDirecion;

@Override
protected void onCreate (Bundle saveInstanceState){
    super.onCreate(saveInstanceState);
    setContentView(R.layout.activity_main2);

    botonRegistrarse = (Button) findViewById(R.id.enviar);
    TextoNombres = (EditText) findViewById(R.id.nombres);
    TextoApellidos = (EditText) findViewById(R.id.apellidos);
    TextoCedula = (EditText) findViewById(R.id.cedula);
    TextoTelefono1 = (EditText) findViewById(R.id.telefono1);
    TextoTelefono2 = (EditText) findViewById(R.id.telefono2);
    TextoDirecion = (EditText) findViewById(R.id.direccion);

    botonRegistrarse.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            new EnvioPOST().execute("http://naikino.com/pizzeria/php/registrar.php");
        }
    });
}

private class EnvioPOST extends AsyncTask<String, Void, String> {
    @Override
    //el metodo doInBackground para hacer en segundo plano
    protected String doInBackground(String... urls) {
        //los parametros son pasados de la ejecucion execute(): url[0] es la url.
        try {

            //url[0] es la url y el 0 indica que vamos ha usar medoto GET
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "No se puede recuperar la pagina web. URL puede ser incorrecto.";

        }
    }

    //onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(String result) {
        Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
    }
}
private String downloadUrl(String myurl) throws IOException {
    Log.i("URL", "" + myurl);
    myurl = myurl.replace(" ", "%20"); /// Cambiamos espacios por %20
    InputStream is = null;
    String respuestaComoString = null;
    // Mostrar solo los primeros 500 carapteres del contenido
    // recuperado de la pagina web.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milisegundos */);
        conn.setConnectTimeout(15000 /* milisegundos */);

        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);

        JSONObject variablesMetodoPost = new JSONObject();

        variablesMetodoPost.put("nombres", TextoNombres.getText().toString());
        variablesMetodoPost.put("apellidos", TextoApellidos.getText().toString());
        variablesMetodoPost.put("cedula", TextoCedula.getText().toString());
        variablesMetodoPost.put("telefono_1", TextoTelefono1.getText().toString());
        variablesMetodoPost.put("telefono_2", TextoTelefono2.getText().toString());
        variablesMetodoPost.put("direccion", TextoDirecion.getText().toString());

        Log.e("params", variablesMetodoPost.toString());
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(obtenerDatosStringAEnviar(variablesMetodoPost));
        writer.flush();
        writer.close();
        os.close();

        //nos conectamos enviando el metodo de conexion y las variables
        //obtenemos una respuesta
        conn.connect();
        int response = conn.getResponseCode();
        Log.d("respuesta", "la respuesta es: " + response);
        is = conn.getInputStream();
        //convertimos el flujo de entrada en texto
        respuestaComoString = readIt(is, len);

    } catch (JSONException e) {
        e.printStackTrace();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        //se asegura de que el InputStream se cierra despues de la aplicacion y
        //es terminado de utilizar
        if (is != null) {
            is.close();
        }
    }

    return respuestaComoString;
}

public String obtenerDatosStringAEnviar(JSONObject params) throws Exception {

    StringBuilder result = new StringBuilder();
    boolean first = true;

    Iterator<String> itr = params.keys();

    while (itr.hasNext()) {

        String key = itr.next();
        Object value = params.get(key);

        if (first)
            first = false;

        else
            result.append("&");

        result.append(URLEncoder.encode(key, "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(value.toString(), "UTF-8"));

    }
    return result.toString();

}
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
    Reader reader = null;
    reader = new InputStreamReader(stream, "UTF-8");
    char[] buffer = new char [len];
    reader.read(buffer);
    return new String(buffer);

}

public void inicio(View view) {
    Intent i = new Intent(this, MainActivity.class);
    startActivity(i);
}

}

En el debut del emulador tengo esto:

I/URL: http://naikino.com/pizzeria/php/registrar.php E/params: {"nombres":"mauricio","apellidos":"vergara","cedula":"1024502218","telefono_1":"1234567","telefono_2":"1234689","direccion":"calle calle"} D/respuesta: la respuesta es: 200 W/EGL_emulation: eglSurfaceAttrib not implemented W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f475bca36c0, error=EGL_SUCCESS

2
  • Es demasiado amplio. Deberías, ya que no te origina error, hacer algun tipo de traza o debug para saber que está pasando y dar mas informacion
    – lois6b
    el 21 nov. 2016 a las 15:48
  • Por favor, edita tu pregunta para que contenga toda la informacion relevante. no lo pongas en los comentarios
    – lois6b
    el 21 nov. 2016 a las 16:24

1 respuesta 1

2

Estas agregando las variables al BufferedWriter y no a la petición:

writer.write(obtenerDatosStringAEnviar(variablesMetodoPost));

Si usas HttpUrlConnection los valores deben agregarse a una lista de NameValuePair para ser enviados mediante POST , ejemplo:

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(10000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();
2
  • no puede resolver símbolo NameValuePair androide! Según veo en la web deberia agregarlos al gradle e importar? el 21 nov. 2016 a las 17:49
  • Usa compileSdkVersion 23.
    – Jorgesys
    el 21 nov. 2016 a las 17:54

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.