· 9 years ago · Jan 10, 2017, 05:22 PM
1private void setAlarm(Uri passuri) throws ParseException {
2
3 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
4 java.util.Calendar cal = java.util.Calendar.getInstance();
5 cal.setTime(sdf.parse(editTextFecha.getText().toString()));
6 Intent intent = new Intent(getBaseContext(), pruebaintento.dos.notif.AlarmReceiver.class);
7 //los extras
8 intent.putExtra("titulo", editTextNombre.getText().toString());
9 PendingIntent pendingIntent = PendingIntent.getBroadcast(
10 getBaseContext(),
11 RQS_1,
12 intent,
13 PendingIntent.FLAG_CANCEL_CURRENT);
14
15 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
16 alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
17
18}
19
20public class DatabaseHandler extends SQLiteOpenHelper{
21 // Ruta por defecto de las bases de datos en el sistema Android.
22 private static String RUTA_BASE_DATOS = "/data/data/pruebaintento.dos/databases/";
23
24 // Nombre de la Base de Datos.
25 private static String NOMBRE_BASE_DATOS = "BDPRUEBA_INFO";
26
27 // Version de la Base de Datos.
28 private static final int VERSION_BASE_DATOS = 1;
29
30 // Objeto Base de Datos.
31 private SQLiteDatabase base_datos;
32
33 // Objeto Contexto.
34 private Context contexto;
35
36 // Constante privada
37 private String SENTENCIA_SQL_CREAR_BASE_DATOS_PERSONAS = "CREATE TABLE if not exists personas (_id INTEGER PRIMARY KEY autoincrement, " +
38 "nombre TEXT, fecha TEXT, zodiaco TEXT, ruta_imagen TEXT)";
39
40 /**
41 * Constructor
42 * Toma referencia hacia el contexto de la aplicación que lo invoca para poder acceder a los 'assets' y
43 * 'resources' de la aplicación.
44 * Crea un objeto DBOpenHelper que nos permitirá controlar la apertura de la base de datos.
45 * @param context
46 */
47 public DatabaseHandler(Context context) {
48 super(context, NOMBRE_BASE_DATOS, null, VERSION_BASE_DATOS);
49 this.contexto = context;
50 }
51
52 @Override
53 public void onCreate(SQLiteDatabase db) {
54 // Se ejecuta la sentencia SQL de creación de la tabla personas.
55 db.execSQL(SENTENCIA_SQL_CREAR_BASE_DATOS_PERSONAS);
56 }
57
58 @Override
59 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
60 // Se elimina la versión anterior de la tabla Personas.
61 db.execSQL("DROP TABLE IF EXISTS Personas");
62
63 // Se crea la nueva versión de la tabla personas.
64 db.execSQL(SENTENCIA_SQL_CREAR_BASE_DATOS_PERSONAS);
65 }
66
67 /**
68 * Metodo publico para insertar una nueva persona.
69 */
70 public void insertarPersona(Persona persona){
71 ContentValues valores = new ContentValues();
72 valores.put("nombre", persona.getNombre());
73 valores.put("fecha", persona.getFecha());
74 valores.put("zodiaco", persona.getZodiaco());
75 valores.put("ruta_imagen", persona.getRutaImagen());
76 this.getWritableDatabase().insert("Personas", null, valores);
77 }
78
79 /**
80 * Metodo publico para actualizar una persona.
81 */
82 public void actualizarRegistros(int id, String nombre, String fecha, String zodiaco, String ruta_imagen){
83 ContentValues actualizarDatos = new ContentValues();
84 actualizarDatos.put("nombre", nombre);
85 actualizarDatos.put("fecha", fecha);
86 actualizarDatos.put("zodiaco", zodiaco);
87 actualizarDatos.put("ruta_imagen", ruta_imagen);
88 String where = "_id=?";
89 String[] whereArgs = new String[] {String.valueOf(id)};
90
91 try{
92 this.getReadableDatabase().update("Personas", actualizarDatos, where, whereArgs);
93 }
94 catch (Exception e){
95 String error = e.getMessage().toString();
96 }
97 }
98
99 /**
100 * Metodo publico que retorna una persona especifica.
101 * @param id
102 * @return
103 */
104 public Persona getPersona(int p_id) {
105 String[] columnas = new String[]{"_id", "nombre", "fecha", "zodiaco", "ruta_imagen"};
106 Cursor cursor = this.getReadableDatabase().query("Personas", columnas, "_id" + "= " + p_id, null, null, null, null);
107
108 if (cursor != null){
109 cursor.moveToFirst();
110 }
111
112 Persona persona = new Persona(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), cursor.getString(3),
113 cursor.getString(4));
114
115 // Retorna la persona especifica.
116 return persona;
117 }
118
119 /**
120 * Metodo publico que cierra la base de datos.
121 */
122 public void cerrar(){
123 this.close();
124 }
125
126 /**
127 * Metodo publico que devuelve todas las personas.
128 * @return
129 */
130 public Cursor obtenerTodasPersonas(){
131 String[] columnas = new String[]{"_id", "nombre", "fecha", "zodiaco", "ruta_imagen"};
132 Cursor cursor = this.getReadableDatabase().query("Personas", columnas, null, null, null, null, null);
133
134 if(cursor != null) {
135 cursor.moveToFirst();
136 }
137 return cursor;
138 }
139
140
141 /**
142 * Metodo publico que elimina una persona especifica.
143 * @param rowId
144 * @return
145 */
146 public boolean eliminaPersona(long id){
147 return this.getWritableDatabase().delete("Personas", "_id" + "=" + id, null) > 0;
148 }
149}
150
151public class AlarmReceiver extends BroadcastReceiver {
152
153 @Override
154 public void onReceive(Context context, Intent intent) {
155
156
157 // Notificación
158
159 NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
160
161 Intent repeating_intent = new Intent(context,MainActivity.class);
162 repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
163
164
165 PendingIntent pendingIntent = PendingIntent.getActivity(context,id,repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
166
167
168 NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
169 .setContentIntent(pendingIntent)
170 .setSmallIcon(R.drawable.ic_launcher)
171 .setContentTitle(intent.getStringExtra("titulo"))
172 .setContentText("¡Hoy es su cumpleaños!")
173 .setAutoCancel(true);
174 builder.setVibrate(new long[] { 300, 300 });
175 builder.setLights(Color.BLUE, 3000, 3000);
176 builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
177 notificationManager.notify(id,builder.build());
178
179 // Fin Notificación
180
181 }
182}
183
184public class Persona implements Serializable{
185 // Atributos de clase
186 private int id;
187 private String nombre;
188 private String fecha;
189 private String zodiaco;
190 private String ruta_imagen;
191
192 /**
193 * Constructor por defecto.
194 */
195 public Persona(){
196 }
197
198 /**
199 * Constructor que se le pasa 4 parametros.
200 * @param p_nombre
201 * @param p_fecha
202 * @param p_zodiaco
203 * @param p_ruta_imagen
204 */
205 public Persona(String p_nombre, String p_fecha, String p_zodiaco, String p_ruta_imagen){
206 setNombre(p_nombre);
207 setFecha(p_fecha);
208 setZodiaco(p_zodiaco);
209 setRutaImagen(p_ruta_imagen);
210 }
211
212 /**
213 * Constructor que se le pasa 5 parametros.
214 * @param p_id
215 * @param p_nombre
216 * @param p_fecha
217 * @param p_zodiaco
218 * @param p_ruta_imagen
219 */
220 public Persona(int p_id, String p_nombre, String p_fecha, String p_zodiaco, String p_ruta_imagen){
221 setId(p_id);
222 setNombre(p_nombre);
223 setFecha(p_fecha);
224 setZodiaco(p_zodiaco);
225 setRutaImagen(p_ruta_imagen);
226 }
227
228 /*
229 * Getters y Setters
230 */
231 /**
232 *
233 * @return
234 */
235 public String getNombre() {
236 return nombre;
237 }
238
239 /**
240 *
241 * @param nombre
242 */
243 public void setNombre(String nombre) {
244 this.nombre = nombre;
245 }
246
247 /**
248 *
249 * @return
250 */
251 public String getFecha() {
252 return this.fecha;
253 }
254
255 /**
256 *
257 * @param fecha
258 */
259 public void setFecha(String fecha) {
260 this.fecha = fecha;
261 }
262
263 /**
264 *
265 * @return
266 */
267 public String getZodiaco() {
268 return zodiaco;
269 }
270
271 /**
272 *
273 * @param zodiaco
274 */
275 public void setZodiaco(String zodiaco) {
276 this.zodiaco = zodiaco;
277 }
278
279 /**
280 *
281 * @return
282 */
283 public int getId(){
284 return this.id;
285 }
286
287 /**
288 *
289 * @param id
290 */
291 public void setId(int id){
292 this.id = id;
293 }
294
295 /**
296 *
297 * @return
298 */
299 public String getRutaImagen(){
300 return this.ruta_imagen;
301 }
302
303 /**
304 *
305 * @param String
306 */
307 public void setRutaImagen(String ruta_imagen){
308 // Si ruta_imagen es null entonces se pone un valor predeterminado.
309 if(ruta_imagen == null){
310 this.ruta_imagen = "No tiene imagen.";
311 }else{
312 this.ruta_imagen = ruta_imagen;
313 }
314 }
315}
316
317public class ImagenAdapter extends SimpleCursorAdapter {
318 // Objetos de clase.
319 private Cursor cursor;
320 private Context contexto;
321 private LayoutInflater mInflater;
322
323
324 static class ViewHolder{
325 TextView textViewNombre;
326 TextView textViewFecha;
327 TextView textViewZodiaco;
328 ImageView thumb_persona;
329 }
330
331 /**
332 * Constructor con 4 parametros.
333 * @param contexto
334 * @param cursor
335 * @param from
336 * @param to
337 */
338 public ImagenAdapter(Context contexto, Cursor cursor, String[] from,
339 int[] to) {
340 super(contexto, R.layout.fila_persona, cursor, from, to);
341 this.contexto = contexto;
342 this.cursor = cursor;
343 this.mInflater = LayoutInflater.from(contexto);
344 }
345
346 public View getView(int position, View convertView, ViewGroup parent) {
347 ViewHolder viewHolder;
348
349 if (convertView == null){
350 convertView = this.mInflater.inflate(R.layout.fila_persona, null);
351 viewHolder = new ViewHolder();
352
353 viewHolder.textViewNombre = (TextView)convertView.findViewById(R.id.persona_nombre);
354 viewHolder.textViewFecha = (TextView)convertView.findViewById(R.id.persona_fecha);
355 viewHolder.textViewZodiaco = (TextView)convertView.findViewById(R.id.persona_zodiaco);
356 viewHolder.thumb_persona = (ImageView)convertView.findViewById(R.id.foto_gallery);
357 convertView.setTag(viewHolder);
358 }else{
359 viewHolder = (ViewHolder)convertView.getTag();
360 }
361 this.cursor.moveToPosition(position);
362
363 viewHolder.textViewNombre.setText(this.cursor.getString(this.cursor.getColumnIndex("nombre")));
364 viewHolder.textViewFecha.setText(this.cursor.getString(this.cursor.getColumnIndex("fecha")));
365 viewHolder.textViewZodiaco.setText(this.cursor.getString(this.cursor.getColumnIndex("zodiaco")));
366
367 // Se obtiene la ruta de la imagen.
368 String ruta_imagen = cursor.getString(cursor.getColumnIndex("ruta_imagen"));
369
370@Override
371 public void onCreate(Bundle savedInstanceState) {
372 super.onCreate(savedInstanceState);
373 setContentView(R.layout.editar_persona);
374
375 // Hace referencia a los objetos xml.
376 butonGuardar = (Button) findViewById(R.id.botonGuardar);
377 butonLimpiar = (Button) findViewById(R.id.botonLimpiar);
378 editTextNombre = (EditText) findViewById(R.id.editTextNombre);
379 editTextFecha = (EditText) findViewById(R.id.editTextFecha);
380 editTextZodiaco = (EditText) findViewById(R.id.editTextZodiaco);
381 imagenPersona = (ImageView) findViewById(R.id.imagenPersona);
382 uriAlarm = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
383
384 // empieza spinner
385
386 Spinner spin = (Spinner) findViewById(R.id.spinnerbasico);
387 CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), flags, zodiaco);
388 spin.setOnItemSelectedListener(this);
389 spin.setAdapter(customAdapter);
390
391 //termina spinner
392
393
394 }
395
396 // spinner
397
398 @Override
399 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
400 String description = zodiaco[position];
401 editTextZodiaco.setText(description);
402 }
403
404
405 @Override
406 public void onNothingSelected(AdapterView<?> parent) {
407
408 }
409
410
411 // termina spinner
412
413
414{
415
416 // Se crea el objeto mensaje.
417 mensaje = new Mensaje(getApplicationContext());
418
419 /**
420 * Al hacer click en el boton imagen se abre una ventana.
421 */
422 imagenPersona.setOnClickListener(new OnClickListener() {
423 public void onClick(View v) {
424 ventanaImagen();
425 }
426 });
427 // Recupera en un Objeto Bundle si tiene valores que fueron pasados como
428 // parametro de una actividad.
429 extras = getIntent().getExtras();
430
431
432 if (estadoEditarPersona()) {
433 editTextNombre.setText(extras.getString("nombre"));
434 editTextFecha.setText(extras.getString("fecha"));
435 editTextZodiaco.setText(extras.getString("zodiaco"));
436 ruta_imagen = extras.getString("ruta_imagen");
437 imagenPersona.setImageBitmap(crearThumb());
438 }
439
440 // Agrega nuevo registro de una persona.
441 butonGuardar.setOnClickListener(new View.OnClickListener() {
442 public void onClick(View v) {
443 if (verificarCampoNombre() && verificarCampoFecha()
444 && verificarCampoZodiaco()) {
445 if (estadoEditarPersona()) {
446 editarPersona();
447 } else {
448 try {
449 setAlarm(uriAlarm);
450 } catch (ParseException e) {
451 e.printStackTrace();
452 }
453 insertarNuevoPersona();
454 }
455 // Finaliza la actividad EditarPersonaActivity.
456 finish();
457 } else {
458 if (editTextNombre.getText().toString().equals("")) {
459 mensaje.mostrarMensajeCorto("Introduzca un Nombre");
460 }
461 if (editTextFecha.getText().toString().equals("")) {
462 mensaje.mostrarMensajeCorto("Introduzca una Fecha");
463 }
464 if (editTextZodiaco.getText().toString().equals("")) {
465 mensaje.mostrarMensajeCorto("Introduzca su Zodiaco");
466 }
467 }
468 }
469 });
470
471 // Limpia los campos.
472 butonLimpiar.setOnClickListener(new View.OnClickListener() {
473 public void onClick(View v) {
474 limpiarCampos();
475 }
476 });
477 }
478
479 /**
480 * Metodo privado que limpia los campos.
481 */
482 private void limpiarCampos() {
483 editTextNombre.setText("");
484 editTextFecha.setText("");
485 editTextZodiaco.setText("");
486 }
487
488 /**
489 * Metodo privado que verifica que se cambio el valor de Nombre o no está en
490 * blanco (vacio).
491 */
492 private boolean verificarCampoNombre() {
493 if (editTextNombre.getText().toString().equals("")) {
494 return false;
495 }
496 return true;
497 }
498
499 /**
500 * Metodo privado que verifica que se cambio el valor de Fecha o no
501 * está en blanco (vacio).
502 */
503 private boolean verificarCampoFecha() {
504 if (editTextFecha.getText().toString().equals("")) {
505 return false;
506 }
507 return true;
508 }
509
510 /**
511 * Metodo privado que verifica que se cambio el valor de la Zodiaco o no está
512 * en blanco (vacio).
513 */
514 private boolean verificarCampoZodiaco() {
515 if (editTextZodiaco.getText().toString().equals("")) {
516 return false;
517 }
518 return true;
519 }
520
521 /**
522 * Metodo privado que insertar una nueva Persona.
523 */
524 private void insertarNuevoPersona() {
525 baseDatos = new DatabaseHandler(EditarPersonaActivity.this);
526
527 try {
528 // Crear objeto Persona.
529 Persona persona = new Persona(editTextNombre.getText().toString(),
530 editTextFecha.getText().toString(), editTextZodiaco
531 .getText().toString(), ruta_imagen);
532
533 // Se inserta una nueva persona.
534 baseDatos.insertarPersona(persona);
535 } catch (Exception e) {
536 mensaje.mostrarMensajeCorto("Error, por favor empieza de nuevo");
537 e.printStackTrace();
538 } finally {
539 // Se cierra la base de datos.
540 baseDatos.cerrar();
541 }
542 }
543
544 /**
545 * Metodo privado que edita una persona existente.
546 */
547 private void editarPersona() {
548 baseDatos = new DatabaseHandler(EditarPersonaActivity.this);
549
550 try {
551 // Crear objeto persona.
552 int id = extras.getInt("id");
553
554 Persona persona = new Persona(id, editTextNombre.getText()
555 .toString(), editTextFecha.getText().toString(),
556 editTextZodiaco.getText().toString(), ruta_imagen);
557
558 baseDatos.actualizarRegistros(id, persona.getNombre(),
559 persona.getFecha(), persona.getZodiaco(),
560 persona.getRutaImagen());
561 setAlarm(uriAlarm);
562 } catch (ParseException e) {
563 e.printStackTrace();
564 mensaje.mostrarMensajeCorto("Se edito correctamente");
565 } catch (Exception e) {
566 mensaje.mostrarMensajeCorto("Error al querer editarlo, por favor intentelo de nuevo");
567 e.printStackTrace();
568 } finally {
569 baseDatos.cerrar();
570 }
571 }
572
573 /**
574 *
575 */
576 public boolean estadoEditarPersona() {
577 // Si extras es diferente a null es porque tiene valores. En este caso
578 // es porque se quiere editar una persona.
579 if (extras != null) {
580 return true;
581 } else {
582 return false;
583 }
584 }
585
586
587 private void setAlarm(Uri passuri) throws ParseException {
588
589 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
590 java.util.Calendar cal = java.util.Calendar.getInstance();
591 cal.setTime(sdf.parse(editTextFecha.getText().toString()));
592 Intent intent = new Intent(getBaseContext(), vrteam.birthday.notif.AlarmReceiver.class);
593 //los extras
594 intent.putExtra("titulo", editTextNombre.getText().toString());
595 PendingIntent pendingIntent = PendingIntent.getBroadcast(
596 getBaseContext(),
597 RQS_1,
598 intent,
599 PendingIntent.FLAG_CANCEL_CURRENT);
600
601 AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
602 alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pendingIntent);
603
604 }
605
606 /**
607 * Metodo privado que abre la ventana.
608 */
609 private void ventanaImagen() {
610 try {
611 final CharSequence[] items = {"Seleccionar de la galerÃa"};
612
613 AlertDialog.Builder builder = new AlertDialog.Builder(this);
614 builder.setTitle("Seleccionar una foto");
615 builder.setItems(items, new DialogInterface.OnClickListener() {
616 public void onClick(DialogInterface dialog, int item) {
617 switch (item) {
618 case 0:
619 Intent intentSeleccionarImagen = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
620 intentSeleccionarImagen.setType("image/*");
621 startActivityForResult(intentSeleccionarImagen, SELECCIONAR_IMAGEN);
622 break;
623 }
624 }
625 });
626 AlertDialog alert = builder.create();
627 alert.show();
628 } catch (Exception e) {
629 mensaje.mostrarMensajeCorto("El error es: " + e.getMessage());
630 }
631 }
632
633 @Override
634 public void onActivityResult(int requestCode, int resultCode, Intent data) {
635 super.onActivityResult(requestCode, resultCode, data);
636
637 try {
638 if (requestCode == SELECCIONAR_IMAGEN) {
639 if (resultCode == Activity.RESULT_OK) {
640 Uri selectedImage = data.getData();
641 ruta_imagen = obtieneRuta(selectedImage);
642 imagenPersona.setImageBitmap(crearThumb());
643 }
644 }
645 } catch (Exception e) {
646 }
647
648 }
649
650 private Bitmap getBitmap(String ruta_imagen) {
651 // Objetos.
652 File imagenArchivo = new File(ruta_imagen);
653 Bitmap bitmap = null;
654
655 if (imagenArchivo.exists()) {
656 bitmap = BitmapFactory.decodeFile(imagenArchivo.getAbsolutePath());
657 }
658 return bitmap;
659 }
660
661 /**
662 * Metodo privado
663 *
664 * @param uri
665 * @return
666 */
667 private String obtieneRuta(Uri uri) {
668 String[] projection = {android.provider.MediaStore.Images.Media.DATA};
669 Cursor cursor = managedQuery(uri, projection, null, null, null);
670 int column_index = cursor
671 .getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
672 cursor.moveToFirst();
673 return cursor.getString(column_index);
674 }
675
676 @Override
677 public boolean onOptionsItemSelected(MenuItem item) {
678 switch (item.getItemId()) {
679 case android.R.id.home:
680 Intent intent = new Intent(this, MainActivity.class);
681 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
682 startActivity(intent);
683
684 // Cerrar EditarPersonaActivity.
685 EditarPersonaActivity.this.finish();
686
687 return true;
688 default:
689 return super.onOptionsItemSelected(item);
690 }
691 }
692
693 @Override
694 protected void onDestroy(){
695 super.onDestroy();
696
697 // Coloco todos los objetos en null.
698 imagenPersona = null;
699
700 // LLama al recolector de basura.
701 System.gc();
702 }
703
704 /**
705 * Metodo privado que crea un Bitmap (thumb).
706 */
707 private Bitmap crearThumb(){
708 Bitmap bitmap = getBitmap(ruta_imagen);
709 BitmapFactory.Options opciones = new BitmapFactory.Options();
710 opciones.inJustDecodeBounds = true;
711 BitmapFactory.decodeFile(ruta_imagen, opciones);
712
713 int scaleW = opciones.outWidth / 854 + 1;
714 int scaleH = opciones.outHeight / 480 + 1;
715 int scale = Math.max(scaleW, scaleH);
716
717 opciones.inJustDecodeBounds = false;
718 opciones.inSampleSize = scale;
719 opciones.inSampleSize = scale;
720 bitmap = BitmapFactory.decodeFile(ruta_imagen, opciones);
721 return bitmap;
722 }
723 }
724
725@Override
726public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
727 super.onCreateContextMenu(menu, v, menuInfo);
728 android.view.MenuInflater inflater = getMenuInflater();
729 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
730 inflater.inflate(R.menu.opciones_personas, menu);
731}
732
733/**
734 * Metodo publico que se sobreescribe. En este metodo colocamos las acciones de las opciones del menu contextual
735 * para el ListView de personas.
736 */
737@Override
738public boolean onContextItemSelected(android.view.MenuItem item) {
739 AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
740
741 switch (item.getItemId()) {
742 case R.id.menu_contextual_editar_persona:
743 editarPersona((int)info.id);
744 return true;
745 case R.id.menu_contextual_eliminar_persona:
746 eliminarPersona((int)info.id);
747 recuperarTodasPersonas();
748 return true;
749 default:
750 return super.onContextItemSelected((android.view.MenuItem) item);
751 }
752}
753
754@Override
755protected void onStart(){
756 super.onStart();
757}
758
759@Override
760protected void onResume(){
761 super.onResume();;
762}
763
764/**
765 * Metodo privado que recupera todos las personas existentes de la base de datos.
766 */
767private void recuperarTodasPersonas() {
768 try{
769 baseDatos = new DatabaseHandler(this);
770
771 // Devuelve todas las personas en el objeto Cursor.
772 Cursor cursor = baseDatos.obtenerTodasPersonas();
773
774 String[] from = new String[]{
775 "nombre",
776 "fecha",
777 "zodiaco",
778 "ruta_imagen"
779 };
780
781 int[] to = new int[]{
782 R.id.persona_nombre,
783 R.id.persona_fecha,
784 R.id.persona_zodiaco,
785 R.id.foto_gallery,
786 };
787 cursorAdapter = new ImagenAdapter(this, cursor, from, to);
788 listViewPersonas.setAdapter(cursorAdapter);
789 }catch(Exception e){
790 Log.d("Error", "El mensaje de error es: " + e.getMessage());
791 }finally{
792 // Se cierra la base de datos.
793 baseDatos.cerrar();
794 }
795}
796
797/**
798 * Metodo publico que edita una persona.
799 * @param p_id
800 */
801public void editarPersona(int p_id){
802 // Si el p_id es 0, entonces se crea una nueva persona.
803 if(p_id == 0){
804 // Se dirige a la actividad EditarPersonaActivity.
805 Intent actividad_editarPersona = new Intent(MainActivity.this, EditarPersonaActivity.class);
806 startActivityForResult(actividad_editarPersona, CODIGO_RESULT_EDITAR_PERSONA);
807 }else{
808 // Recupera una persona especifica.
809 Persona persona;
810
811 try{
812 persona = baseDatos.getPersona(p_id);
813
814 // Se dirige a la actividad EditarPersonaActivity.
815 Intent actividad_editarPersona = new Intent(this, EditarPersonaActivity.class);
816
817 // Se le coloca parametros para enviar a la actividad EditarPersonaActivity.
818 actividad_editarPersona.putExtra("id", p_id);
819 actividad_editarPersona.putExtra("nombre", persona.getNombre());
820 actividad_editarPersona.putExtra("fecha", persona.getFecha());
821 actividad_editarPersona.putExtra("zodiaco", persona.getZodiaco());
822 actividad_editarPersona.putExtra("ruta_imagen", persona.getRutaImagen());
823
824 startActivityForResult(actividad_editarPersona, CODIGO_RESULT_EDITAR_PERSONA);
825 }catch (Exception e){
826 Toast.makeText(getApplicationContext(), "Error al editar", Toast.LENGTH_SHORT).show();
827 e.printStackTrace();
828 }finally{
829 baseDatos.cerrar();
830 }
831 }
832}
833
834/**
835 * Metodo privado que elimina una persona.
836 * @param id_persona
837 */
838private void eliminarPersona(int id_persona){
839 // Objetos.
840 AlertDialog.Builder mensaje_dialogo = new AlertDialog.Builder(this);
841
842 final int v_id_persona = id_persona;
843
844 mensaje_dialogo.setTitle("Importante");
845 mensaje_dialogo.setMessage("¿Está seguro de eliminar esta persona?");
846 mensaje_dialogo.setCancelable(false);
847 mensaje_dialogo.setPositiveButton("Confirmar", new DialogInterface.OnClickListener() {
848 public void onClick(DialogInterface dialogo1, int id) {
849 try{
850 baseDatos.eliminaPersona(v_id_persona);
851
852 recuperarTodasPersonas();
853 }catch(Exception e){
854 Toast.makeText(getApplicationContext(), "Error al eliminar!", Toast.LENGTH_SHORT).show();
855 e.printStackTrace();
856 }finally{
857 baseDatos.cerrar();
858 }
859 }
860 });
861 mensaje_dialogo.setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {
862 public void onClick(DialogInterface dialogo1, int id) {
863 recuperarTodasPersonas();
864 }
865 });
866 mensaje_dialogo.show();
867}
868@Override
869protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
870 super.onActivityResult(requestCode, resultCode, intent);
871 recuperarTodasPersonas();
872}