CREATE TABLE persona ( id_persona serial NOT NULL, nombre character varying(120) NOT NULL, direccion character varying(90) NOT NULL, edad integer NOT NULL, email character varying(120) NOT NULL, contrasena character varying(120) NOT NULL, CONSTRAINT id_persona_pkey PRIMARY KEY (id_persona) )
conexion.php
Contenidos
<?php $username = "postgres"; $password = "12345"; $host = "localhost"; $port= "5433"; $dbname = "BD_persona"; try { $db = new PDO("pgsql:host={$host};port={$port};dbname={$dbname};", $username,$password); } catch(PDOException $ex) { die("Error al conectarse a la base de datos: " . $ex->getMessage()); } $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); session_start(); ?>
login.php
<?php require("conexion.php"); if (!empty($_POST)) { $query = " SELECT id_persona, email, contrasena FROM persona WHERE email = :email "; $query_params = array( ':email' => $_POST['email'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Error en la BD, vuelve a intetarlo"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } $validated_info = false; $row = $stmt->fetch(); if ($row) { if ($_POST['contrasena'] === $row['contrasena']) { $login_ok = true; } } if ($login_ok) { $response["success"] = 1; $response["message"] = "LOGIN CORRECTO!"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } else { $response["success"] = 0; $response["message"] = "LOGIN INCORRECTO"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } } ?>
registrar.php
<?php require("conexion.php"); if (!empty($_POST)) { if (empty($_POST['email']) || empty($_POST['contrasena'])) { $response["success"] = 0; $response["message"] = "Ingrese el email y la contrasena"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } $query= " SELECT 1 FROM persona WHERE email = :email"; $query_params = array( ':email' => $_POST['email'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Database Error!"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } $row = $stmt->fetch(); if ($row) { $response["success"] = 0; $response["message"] = "Error el usuario ya existe"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } $query = "INSERT INTO persona ( nombre, direccion, edad, email, contrasena ) VALUES ( :nombre, :direccion, :edad, :email, :contrasena ) "; $query_params = array( ':nombre' => $_POST['nombre'], ':direccion' => $_POST['direccion'], ':edad' => $_POST['edad'], ':email' => $_POST['email'], ':contrasena' => $_POST['contrasena'] ); try { $stmt = $db->prepare($query); $result = $stmt->execute($query_params); } catch (PDOException $ex) { $response["success"] = 0; $response["message"] = "Error en la BD. Vuelve a intentarlo"; die(json_encode($response, JSON_UNESCAPED_UNICODE)); } $response["success"] = 1; $response["message"] = "El usuario se ha agregado correctamente"; echo json_encode($response, JSON_UNESCAPED_UNICODE); } ?>
Empezamos por las configuraciones de nuestra App: primeros nos vamos a nuestro build.gradle y agregamos la siguiente linea:
Esta librería nos sirve para usar todos los atributos de apache y sino sabes donde ponerlo observa la siguiente imagen:
acitivity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView2" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" app:srcCompat="@drawable/sesion" /> <Button android:id="@+id/btnRegistro" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/btnLogin" android:layout_alignParentBottom="true" android:layout_alignRight="@+id/btnLogin" android:layout_marginBottom="25dp" android:text="REGISTRAR" /> <Button android:id="@+id/btnLogin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/btnRegistro" android:layout_alignLeft="@+id/txtPassword" android:layout_alignRight="@+id/txtPassword" android:text="Login" /> <EditText android:id="@+id/txtPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/btnLogin" android:layout_centerHorizontal="true" android:ems="10" android:inputType="textPassword" > <requestFocus /> </EditText> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/txtPassword" android:layout_alignLeft="@+id/txtPassword" android:layout_marginLeft="22dp" android:text="Ingrese Contraseña" /> <EditText android:id="@+id/txtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/TextView01" android:layout_centerHorizontal="true" android:ems="10" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignStart="@+id/txtEmail" android:layout_centerVertical="true" android:text="Ingrese Correo" /> </RelativeLayout>
activity_registrar
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/textView5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView4" android:layout_alignStart="@+id/textView4" android:layout_marginBottom="45dp" android:text="NOMBRE" /> <EditText android:id="@+id/etxtNombre" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView4" android:layout_alignStart="@+id/textView5" android:ems="10" android:inputType="textPersonName" /> <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/etxtEdad" android:layout_alignStart="@+id/etxtEdad" android:text="EDAD" /> <EditText android:id="@+id/etxtEdad" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView3" android:layout_centerHorizontal="true" android:ems="10" android:inputType="number" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/etxtDireccion" android:layout_alignStart="@+id/etxtDireccion" android:text="DIRECCION" /> <EditText android:id="@+id/etxtDireccion" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/textView2" android:layout_alignStart="@+id/textView2" android:ems="10" /> <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/edtPassword" android:layout_centerVertical="true" android:text="EMAIL" /> <EditText android:id="@+id/etxtEmail" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/textView2" android:layout_below="@+id/textView2" android:ems="10" android:inputType="textEmailAddress" /> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/etxtEmail" android:layout_below="@+id/etxtEmail" android:text="PASSWORD" /> <EditText android:id="@+id/edtPassword" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/TextView01" android:layout_centerHorizontal="true" android:ems="10" /> <Button android:id="@+id/register" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignRight="@+id/edtPassword" android:layout_below="@+id/edtPassword" android:text="REGISTRAR" /> </RelativeLayout>
MainActivity
public class JSONParser { static InputStream is = null; static JSONObject jObj = null; static String json = ""; public JSONParser() { } public JSONObject getJSONFromUrl(final String url) { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } public JSONObject makeHttpRequest(String url, String method, List params) { try { if(method == "POST"){ // request method is POST // defaultHttpClient DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); }else if(method == "GET"){ DefaultHttpClient httpClient = new DefaultHttpClient(); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } try { BufferedReader reader = new BufferedReader(new InputStreamReader( is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parse the string to a JSON object try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } return jObj; } }
Registrar
public class Registrar extends Activity implements OnClickListener{ private EditText email, pass,edad,direccion,nombre; private Button mRegister; CharSequence text = "Usuario creado!"; private ProgressDialog pDialog; JSONParser jsonParser = new JSONParser(); private static final String REGISTER_URL ="http://192.168.8.133/postgresql/login/registrar.php"; private static final String TAG_SUCCESS = "Exito"; private static final String TAG_MESSAGE = "Mensaje"; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.activity_registrar); email = (EditText)findViewById(R.id.etxtEmail); pass = (EditText)findViewById(R.id.edtPassword); edad = (EditText)findViewById(R.id.etxtEdad); direccion = (EditText)findViewById(R.id.etxtDireccion); nombre = (EditText)findViewById(R.id.etxtNombre); mRegister = (Button)findViewById(R.id.register); mRegister.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub new CreateUser().execute(); } class CreateUser extends AsyncTask<String, String, String> { @Override protected void onPreExecute() { super.onPreExecute(); pDialog = new ProgressDialog(Registrar.this); // pDialog.setMessage("Usuario creado..."); Toast.makeText(Registrar.this,"Usuario creado", Toast.LENGTH_SHORT).show(); pDialog.setIndeterminate(false); pDialog.setCancelable(true); pDialog.show(); } @Override protected String doInBackground(String... args) { // TODO Auto-generated method stub // Check for success tag int success; String vNombre = nombre.getText().toString(); String vDireccion = direccion.getText().toString(); String vEdad = edad.getText().toString(); String vEmail = email.getText().toString(); String vPassword = pass.getText().toString(); try { // Los parametros en comillas debe ser igual a tu BD List params = new ArrayList(); params.add(new BasicNameValuePair("nombre", vNombre)); params.add(new BasicNameValuePair("direccion", vDireccion)); params.add(new BasicNameValuePair("edad", vEdad)); params.add(new BasicNameValuePair("email", vEmail)); params.add(new BasicNameValuePair("contrasena", vPassword)); Log.d("Empezando", "Solicitud!"); //Posting email data to script JSONObject json = jsonParser.makeHttpRequest( REGISTER_URL, "POST", params); // full json response Log.d("Registrando ", json.toString()); success = json.getInt(TAG_SUCCESS); if (success == 1) { Log.d("Usuario Creado!", json.toString()); finish(); return json.getString(TAG_MESSAGE); }else{ Log.d("Fallo el registro!", json.getString(TAG_MESSAGE)); return json.getString(TAG_MESSAGE); } } catch (JSONException e) { e.printStackTrace(); } return null; } protected void onPostExecute(String file_url) { pDialog.dismiss(); if (file_url != null){ Toast.makeText(Registrar.this, file_url, Toast.LENGTH_LONG).show(); } } } }
Con eso hemos terminado la clase Mostrar y el activity_mostrar lo crean pero no es necesario que agreguen nada como les comente lineas arriba.
y debería quedarles algo así como la siguiente imagen:
Ahora les dejo los permisos que hay que poner en nuestro AndroidManifest.
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.androfast.pc.apploginandroidpostgresql"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category :name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".Mostrar" android:screenOrientation="landscape"/> <activity android:name=".Registrar" /> </application> </manifest>
Con eso hemos culminado a continuación les dejo para que descarguen la aplicación:
Hola soy Alex Céspedes fundador de ANDROFAST, programo algunas cosas por diversión, me gusta aprender cosas nuevas y estoy pendiente de todo lo que tenga que ver con tecnología. Este blog lo cree para todas las personas que tengan dificultades en la programación, para ser sincero nunca fui bueno y reprobé algunos cursos de programación, pero mis ganas de aprender pudieron más. SI YO PUEDO TU PUEDES ANIMO!
Excelente mi profe
Acabando con postgresql, empezare con SQL server ahí me hechas una mano.
Hola, muy interesante pero que paso con los web services en que parte del android los metiste, creaste una carpeta en el mismo android studio o es que estas usando XAMPP.
Gracias.
Hola Morgan en este tutorial se usa xampp
Excelente tutorial estimado, una consulta con que versión de android studio lo hiciste?