package com.example.marcelosegovia.servicioswebunid;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Marcelo Segovia on 15/11/2017.
*/
public class AgregarContactoActivity extends AppCompatActivity implements View.OnClickListener{
Intent ventana;
String usuario;
EditText nombre;
EditText apodo;
EditText movil;
EditText casa;
EditText email;
Button guardar;
String IP = "http://192.168.1.7/agenda";
String INSERT = IP + "/insertar_contacto.php";
ObtenerWebService hiloconexion;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_agregar_contacto);
Bundle datos = getIntent().getExtras();
usuario = datos.getString("nombre");
nombre = (EditText)findViewById(R.id.nombre);
apodo = (EditText)findViewById(R.id.apodo);
movil = (EditText)findViewById(R.id.movil);
casa = (EditText) findViewById(R.id.casa);
email = (EditText) findViewById(R.id.email);
guardar = (Button)findViewById(R.id.guardar);
guardar.setOnClickListener(this);
}
@Override
public void onClick(View v) {
hiloconexion = new ObtenerWebService();
hiloconexion.execute(INSERT,"5",nombre.getText().toString(),apodo.getText().toString(),
movil.getText().toString(),casa.getText().toString(),email.getText().toString());
}
public class ObtenerWebService extends AsyncTask<String,Void,String> {
@Override
protected String doInBackground(String... params) {
String cadena = params[0];
URL url = null; // Url de donde queremos obtener información
String devuelve ="";
try {
HttpURLConnection urlConn;
DataOutputStream printout;
DataInputStream input;
url = new URL(cadena);
urlConn = (HttpURLConnection) url.openConnection();
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(true);
urlConn.setRequestProperty("Content-Type", "application/json");
urlConn.setRequestProperty("Accept", "application/json");
urlConn.connect();
//Creo el Objeto JSON
JSONObject jsonParam = new JSONObject();
jsonParam.put("nombre", params[2]);
jsonParam.put("apodo", params[3]);
jsonParam.put("movil", params[4]);
jsonParam.put("casa", params[5]);
jsonParam.put("email", params[6]);
// Envio los parámetros post.
OutputStream os = urlConn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(jsonParam.toString());
writer.flush();
writer.close();
int respuesta = urlConn.getResponseCode();
StringBuilder result = new StringBuilder();
if (respuesta == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
while ((line=br.readLine()) != null) {
result.append(line);
}
//Creamos un objeto JSONObject para poder acceder a los atributos (campos) del objeto.
JSONObject respuestaJSON = new JSONObject(result.toString()); //Creo un JSONObject a partir del StringBuilder pasado a cadena
//Accedemos al vector de resultados
String resultJSON = respuestaJSON.getString("estado"); // estado es el nombre del campo en el JSON
if (resultJSON == "1") {
devuelve = "Contacto guardado correctamente";
} else if (resultJSON == "2") {
devuelve = "El contacto no pudo guardarse";
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return devuelve;
}
@Override
protected void onCancelled(String s) {
super.onCancelled(s);
}
@Override
protected void onPostExecute(String s) {
verifica(s);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
public void verifica(String s){
if (s.equals("Contacto guardado correctamente") ){
Toast.makeText(this, nombre.getText(), Toast.LENGTH_SHORT).show();
Toast.makeText(this, "Ha sido registrado", Toast.LENGTH_SHORT).show();
ventana = new Intent(AgregarContactoActivity.this, keyActivity.class);
ventana.putExtra("nombre", usuario);
startActivity(ventana);
}else {
Toast.makeText(this, "No se pudo completar el registro", Toast.LENGTH_SHORT).show();
nombre.setText("");
apodo.setText("");
movil.setText("");
casa.setText("");
email.setText("");
}
}
}