Tuesday, October 27, 2020

CONSULTA BD, ANDROID STUDIO

 PRACTICA 10:  Android: Consultar Productos

Ing. Honoria Reyes Macedo 

IDE: Android Studio

Lenguaje de programación para móviles: Java

Sistema Operativo de desarrollo: Windows

Sistema Operativo de Ejecución: Android

Base de datos: SQLite

 

INTRODUCCION

 En esta práctica se hace una consulta en la base de datos SQLite.

La información se presenta organizada en un componente GridView que se llena mediante un adaptador.

El adaptador pone la información de cada producto dentro de un layout ítem. Y al final los envía al GridView

 

ACTIVIDADES

 

1.- En la carpeta drawable  guardar un icono del producto con nombre no.png

2.- En el archivo strings.xml

 - Cambiar la leyenda de la etiqueta “menu_gallery”, poner la leyenda Libros en Existencia (De acuerdo al tema que se escogió).



3.- En el archivo fragment_gallery.xml agregar un componente GridView


- Modificarle 5 atributos:

 gravity = center    

horizontalSpacing = 10dp  

id  = gridVProductos  

numColumns = 2    

verticalSpacing   =  10dp




- Quedaría así, posteriormente quitaremos lo que corresponde al TextView



4.- Crear un nuevo Layout para organizar el contenido de la consulta

  - Generar un Layout(xml) que se llame producto_items





- Agregar los siguientes componentes:

 

1 ImageView con id= imgViewProd  y  background= @drawable/no

1 TextView con id=textVProd

1 TextView con id=textVPrecio

 El LinearLayout deberá ser orientation = vertical



- Sus atributos quedarían así:

- En modo Codigo quedaria así:



5.- Editar la clase ProductoADO 

Agregar el método llenaProd() y declarar la variable ObjProd;




- Sus librerías quedarían así:
 import android.content.ContentValues;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.text.SimpleDateFormat;
import java.util.ArrayList;



6.- Crear una clase adapter

6.1- Crear la clase ProductoAdapter para adaptar los valores de producto en un GridView


6.2 Implementar sus métodos





Quedaría así:



6.3- Modificar el contenido de sus métodos, agregar su constructor y agregar la clase ViewHolder (texto rojo)


package com.example.control_hrm;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;

public class ProductoAdapter extends BaseAdapter {
    private Context context;
    private  int layout;
    private ArrayList<Producto> arrayProducto;

    public ProductoAdapter(Context context, int layout, ArrayList<Producto> productos) {
        this.context= context;
        this.layout = layout;
        this.arrayProducto = productos;
    }

    @Override
    public int getCount() {
        return arrayProducto.size();
    }
    @Override
    public Object getItem(int i) {
        return arrayProducto.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View row = view;
        ViewHolder holder = new ViewHolder();
        String archivo;
        if(row == null){
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(layout, null);
            holder.loc_textVProd = (TextView) row.findViewById(R.id.textVProd);
            holder.loc_textVPrecio = (TextView) row.findViewById(R.id.textVPrecio);
            holder.loc_imgViewProd = (ImageView) row.findViewById(R.id.imgViewProd);
            row.setTag(holder);
        }
        else {
            holder = (ViewHolder) row.getTag();
        }
        Producto prod = arrayProducto.get(i);
        holder.loc_textVProd.setText(prod.getNombreprod());
        holder.loc_textVPrecio.setText(String.valueOf(prod.getPrecioprod()));
        archivo = prod.getFotoprod();

        if (archivo==null){archivo="no";}else{
               String[] palabra = archivo.split("\\.");
               archivo = palabra[0];
        }

        String getPkg=context.getPackageName();
        int aux=context.getResources().getIdentifier(archivo, "drawable",getPkg);
        holder.loc_imgViewProd.setImageResource(aux);
        return row;

    }
    private class ViewHolder{
        ImageView loc_imgViewProd;
        TextView loc_textVProd, loc_textVPrecio;
    }

}


7.- Modificar el archivo GalleryFragment



Al Reconstruir y Ejecutar quedaria así:





************************************************************************

ANEXO I: Insertar datos directamente en la Base de Datos

Agregar el procedimiento insertarValorProd() a la clase ProductoADO 
(líneas en azul). 
Modificar el nombre de las imágenes por las que se tienen en drawable 

Nota: Se tienen que tener al menos 3 imágenes de productos guardadas en la carpeta drawable





Agregar la llamada del procedimiento creado dentro del procedimiento  llenaProd (línea en azul)

Nota: Solo ejecutarlo una vez, y borrar esta línea para que no provoque error por claves duplicadas



********************************************************************

ANEXO II

DBhelper.java

package com.example.control_hrm;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;

public class DBhelper extends SQLiteOpenHelper {
Producto campohelp = new Producto();
static final String DB_NAME = "Libros.db";
static final int DB_VERSION = 1;
private final String CREATE_TABLE = "create table if not exists "
+ campohelp.getTabla() + "(" + campohelp.getCampos() + " );";

public DBhelper(@Nullable Context context) {
super(context, DB_NAME, null,DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);

}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + campohelp.getTabla());
onCreate(sqLiteDatabase);
}
}


*****************************************************

Producto.java




package com.example.control_hrm;
import java.util.Date;
public class Producto {
private int cveprod;
private String nombreprod;
private String autorprod;
private double precioprod;
private String fotoprod;
private Date fechacaptura;
private boolean activo;
private String campos;
private String tabla;
public Producto() { }
public Producto(int cveprod, String nombreprod, String autorprod, double precioprod, String fotoprod, Date fechacaptura, boolean activo) {
this.cveprod = cveprod;
this.nombreprod = nombreprod;
this.autorprod = autorprod;
this.precioprod = precioprod;
this.fotoprod = fotoprod;
this.fechacaptura = fechacaptura;
this.activo = activo;
}
public String getTabla(){
this.tabla="producto";
return tabla;
}
public String getCampos(){
this.campos= "cveprod Integer primary key, " +
"nombreprod Text, " +
"autorprod Text, " +
"precioprod Text, " +
"fotoprod Text, " +
"fechacaptura Text, " +
"activo Integer ";
return campos;
}
public int getCveprod() {
return cveprod;
}
public void setCveprod(int cveprod) {
this.cveprod = cveprod;
}
public String getNombreprod() {
return nombreprod;
}
public void setNombreprod(String nombreprod) {
this.nombreprod = nombreprod;
}
public String getAutorprod() {
return autorprod;
}
public void setAutorprod(String autorprod) {
this.autorprod = autorprod;
}
public double getPrecioprod() {
return precioprod;
}
public void setPrecioprod(double precioprod) {
this.precioprod = precioprod;
}
public String getFotoprod() {
return fotoprod;
}
public void setFotoprod(String fotoprod) {
this.fotoprod = fotoprod;
}
public Date getFechacaptura() {
return fechacaptura ;
}
public void setFechacaptura(Date fechacaptura) {
this.fechacaptura = fechacaptura;
}
public boolean isActivo() {
return activo;
}
public void setActivo(boolean activo) {
this.activo = activo;
}
}

*****************************************************
ProductoADO.java




****************************************************************

ANEXO III        AGREGAR UN COMPONENTE MAS A LA CONSULTA

1.- Agregar un TextView con id= textVAutor   (lineas en azul)


2.- Agregar el atributo loc_textVAutor en la clase ViewHolder (línea azul)

3.- Agregar el llenado del atributo loc_textVAutor en el método getView (líneas azules)






--------------------------------------------0---0---------------------------

-----------------------------------------000------000---------------------






Tuesday, October 20, 2020

PRACTICA 009:  ANDROID: EVENTOS EN INTERFAZ

Ing. Honoria Reyes Macedo 


INTRODUCCION

Como buenas prácticas en el diseño de interfaces, es necesario indicar con mensajes o colores el estado en el que se encuentra dicha interfaz.

En esta práctica se usara el wizard para crear un proyecto tipo "Navigation Drawer Activity"  para agregar eventos en un formulario dentro de fragment_home.xml y fragment_home.java. El formulario lo puedes copiar del ANEXO I  de esta práctica antes de empezar con el punto 1 de las actividades. El punto 1.3 se sustituye por el  ANEXO II.

Los que tienen la practica 007, deberán utilizar esa práctica. y trabajar en el formulario fragment_capturaprod  y solo usar el ANEXO III para finalizar


ACTIVIDADES

 1.- Agregar advertencia al guardar si ya existe la clave

1.1 En el archivo strings.xml  agregar las siguientes etiquetas para mensajes (lineas en azul)







1.2 En el archivo fragment_capturaprod.java agregar el siguiente procedimiento:



1.3 En el archivo fragment_capturaprod.java

En el evento OnClick del botón loc_btnGuardar:  

Corregir de acuerdo a las siguientes líneas (en azul)




1,4 Compilar y ejecutar. Quedaría así cuando ya intenta guardar la misma clave




2.- Agregar estilo

2.1 En el archivo styles.xml agregar estilos al componente <EditText>



2.2 En el archivo fragment_capturaprod.xml usar el estilo en los componentes <EditText>




3.- Agregar advertencia si hay datos vacíos

               3.1 En el archivo fragment_capturaprod.java agregar un método validar() 
             antes de cerrar la clase



3.2 En el archivo fragment_capturaprod.java Agregar los eventos siguientes en el método onCreateView()



Quedaría así, si no capturan datos





4.- Agregar el foco al primer campo de captura (En este caso es la clave del producto)

               4.1 En el archivo fragment_capturaprod.java agregar la línea azul dentro del 
            método onCreateView()




Nota:

El color de resalte cuando está el foco en el componente se establece

desde el archivo styles.xml (línea en azul)




Compilar y ejecutar

Observa que cuando entras a registrar, el cursor estará parpadeando en el primer campo


5.-  Agregar caracteristicas

5.1.- Agregar el límite del texto a capturar en los <EditText>



5.2 Hacer la conversión a mayúsculas en el nombre del producto, agregar en el evento (agregar linea azul)








5.3 Agregar color al fondo de las pantallas




Compilar y ejecutar

Hacer que sucedan los eventos:

-          -  capturando una clave existente

-          -  otra dejando un campo en blanco cuando se avanza, y

-         -   que convierta a mayúsculas lo que se escribe









**********************************************************************

**********************************************************************

ANEXO I:  LOS QUE NO TIENEN LA PRACTICA 007

AGREGAR COMPONENTES (DE UN FORMULARIO)

En el proyecto creado con el el wizard tipo "Navigation Drawer Activity" 

Modificar en el archivo  fragment_home.xml :

- Solo copiar los componentes que estan en el contenedor LinearLayout.

- El contenedor que te crea por default, solo se deberá renombrar en el inicio y en el fin por LinearLayout

- Si tiene algún componente como el TextView no borrarlo, dejarlo hasta abajo.


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
android:orientation="vertical"
tools:context=".fragment_capturaprod">
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_cveprod" />
<EditText
android:id="@+id/editCveprod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
android:hint="@string/c_cveprod" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_nombreprod" />
<EditText
android:id="@+id/editNombreprod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/c_nombreprod"
android:inputType="text" />
<TextView
android:id="@+id/textView4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_autorprod" />
<EditText
android:id="@+id/editAutorprod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/c_autorprod"
android:inputType="text" />
<TextView
android:id="@+id/textView5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_fotoprod" />
<Spinner
android:id="@+id/spnFotoprod"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textView6"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_precioprod" />
<EditText
android:id="@+id/editPrecioprod"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="@string/c_precioprod"
android:inputType="numberDecimal" />
<CheckBox
android:id="@+id/chkActivo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/c_activo" />
<Button
android:id="@+id/btnGuardar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/b_guardar" />
</LinearLayout>


*****************************************************************

ANEXO II: ARCHIVO  HomeFragment.java   

Sustituir el método onCreateView() por el siguiente:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.
fragment_home, container, false);

   
loc_editCveprod = (EditText) view.findViewById(R.id.editCveprod);
   
loc_editNombreprod = (EditText) view.findViewById(R.id.editNombreprod);
   
loc_editAutorprod = (EditText) view.findViewById(R.id.editAutorprod);
    
loc_editPrecioprod = (EditText) view.findViewById(R.id.editPrecioprod);
   
loc_chkActivo = (CheckBox) view.findViewById(R.id.chkActivo);
   
loc_btnGuardar = (Button) view.findViewById(R.id.btnGuardar);
   
loc_spnFotoprod=(Spinner) view.findViewById(R.id.spnFotoprod);

     loc_btnGuardar.setOnClickListener(new View.OnClickListener() {

        @Override
       
public void onClick(View view) {
           
try {

                                               showDialogError(Integer.valueOf(
loc_editCveprod.getText().toString()));

           
} catch (Exception e) {
                Log.d(
"MyApp", "Error:......................... " + e.getMessage());
            }
        }
    });

   
return  view;
}

 

**************************************************************************

ANEXO III: Otra forma de agregar eventos. Declarando primero el objeto del evento y después usarlo

                     en el escuchador setOnFocusChangeListener






---------------------------------------0--0-----------------------------------

-----------------------------------000---000--------------------------------


FLEXSLIDER HTML5

  PRACTICA 020: HTML: FLEXSLIDER Ing. Honoria Reyes Macedo  IDE: Dreamweaver, Atom o Block de notas Lenguaje de paginas ESTATICAS: HTML...