manual básico de android v2.0
TRANSCRIPT
Intel Universidad Peruana Unión – Filial Juliaca
01/01/2014
UNIVERSIDAD PERUANA UNIÓN
Facultad de Ingeniería y Arquitectura
E.A.P. de Ingeniería de Sistemas
Manual Básico de Programación en Android
Autor: Ing. David Mamani Pari
2014
FILIAL JULIACA
ÍNDICE
1. INTRODUCCIÓN ..................................................................................................................................... 2
2. FUNDAMENTOS E INTERFAZ DE USUARIO ........................................................................................... 2
2.1. Plataforma de Desarrollo .................................................................................................................. 2
2.2. Arquitectura del Sistema Operativo Android ................................................................................... 4
2.3. Configuración ..................................................................................................................................... 4
2.4. Aplicación en Android ....................................................................................................................... 9
3. INTENT Y SERVICIOS ............................................................................................................................11
3.1. Intent y Servicios .............................................................................................................................11
4. PERSISTENCIA DE DATOS – ANDROID SQLite .....................................................................................12
4.1. Introducción a SQLite ......................................................................................................................12
4.2. SQLiteOpenHelper ...........................................................................................................................13
4.3. Mantenimiento CRUD con SQLite ...................................................................................................13
4.4. Ejemplo de Aplicación ....................................................................................................................... 0
5. SERVICIOS WEB EN ANDROID .............................................................................................................36
5.1. Introducción a Web Service ............................................................................................................36
5.2. JSON .................................................................................................................................................36
5.3. Ejemplo de Aplicación .....................................................................................................................36
CONTENIDO
1. INTRODUCCIÓN
En el presente documento se presenta un pequeño manual de configuración de herramientas y el
desarrollo de aplicaciones para dispositivos con sistema operativo android (Celulares y Tablets).
Muestra los pasos básicos a seguir en la configuración del IDE, generación de APK y un ejemplo de
control de gastos personales, finalmente un ejemplo de consumo de Web Service a través de SOAP
usando JSON.
2. FUNDAMENTOS E INTERFAZ DE USUARIO
2.1. Plataforma de Desarrollo
Eclipse
Android SDK
Imagen N 01: IDE de Desarrollo Eclipse - Integrado con el Plugin de Android.
El IDE de desarrollo Eclipse debe estar
integrado con el plugin de android
para el Eclipse. Y deben aparecer esos
2 iconos.
Imagen N 02: Configuración de Android SDK.
Imagen N 03: Actualización de las APIS de la versión de Android.
Se debe configurar la ruta donde se
encuentra el SDK de android.
El SDK Android debe estar actualizado
con sus diferentes versiones o al
menos un mínimo de la versión y uno
el más reciente a fin de probar la
compatibilidad de las aplicaciones a
desarrollar.
2.2. Arquitectura del Sistema Operativo Android
Imagen N 04: Arquitectura del Sistema Operativo Android.
2.3. Configuración
Configurar el Emulador de Android:
Para crear y ejecutar el emulador Android pulsaremos en el botón "Android Virtual Device
Manager" - "Dentro del IDE de desarrollo Eclipse”
Imagen N 05: Paso 1 para configurar el Emulador de Android.
Se iniciará la aplicación "Android Virtual Device Manager", pulsaremos "Create" para crear un
nuevo dispositivo virtual emulado:
Imagen N 06: Paso 2 para configurar el Emulador de Android.
Configuración de Android Virtual Device Manager
AVD Name: nombre que identificará el dispositivo si tenemos varios.
Device: seleccionaremos el dispositivo que queramos emular, por ejemplo "Galaxy Nexus".
Target: versión de Android a emular, por ejemplo Android 4.3 - API Level 18".
CPU/ABI: Por defecto se seleccionará ARM (armeabi-v7a), sin embargo en algunas versiones de
da a elegir, o en las versionas anteriores se selecciona automáticamente.
Skin: Es la sección donde configuramos lo referido con la pantalla. Se puede seleccionar el tipo
de pantalla automáticamente o ingresar la resolución.
Front/Back Camera: Para activar la emulación de la cámara delantera y trasera
Memory Options: cantidad de RAM que se asignará al emulador.
Internal Storage: capacidad en MB del almacenamiento interno.
SD Card: capacidad en MB de la tarjeta de memoria SD.
Una vez elegida la personalización del dispositivo virtual pulsaremos "OK" para crearlo:
Imagen N 07: Paso 3 para configurar el Emulador de Android.
Para iniciar el emulador o simular un dispositivo móvil android
Imagen N 08: Ejecutando el Emulador de Android.
Se abrirá la ventana del emulador y se iniciará la carga del sistema, y ya podremos disponer de un
emulador de dispositivo de Android que será exactamente igual que Android en un Smartphone.
Imagen N 09: Emulador en ejecución de Android.
Configuración General de ejecución de aplicaciones:
Imagen N 10: Ignorar Problemas de empaquetado al momento de generar el APK.
Configuración en la Aplicación:
Imagen N 11: Problemas al generar el APK.
Imagen 0X: Error al Momento de Generar el APK.
Imagen 12: Agregar en Resources el código Sombreado.
[xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation"].
2.4. Aplicación en Android
Imagen 0x: Primera Aplicación en Android
Imagen N 0X: Creando el Método Sumar y dando acción en OnClick.
Implementando en la Clase MainActivity.java
Cuadro N 0X: Integrando elementos de la vista con java.
public void sumar(View v){ int a=Integer.parseInt(valora.getText().toString()); int b=Integer.parseInt(valorb.getText().toString()); int resultado=a+b; mostrarResulado.setText(String.valueOf(resultado));}
Cuadro N 0X: Método Sumar en Java.
Imagen 0X: Mostrando el Resultado de la Operación.
3. INTENT Y SERVICIOS
3.1. Intent y Servicios
Pasar parámetros de una vista otra vista.
Intent inten=new Intent();
inten.putExtra("nombre", txtNombre.getText().toString());
inten.setClass(this, RegistroDatos.class);
startActivity(inten);
Cuadro N 0X: Forma de enviar parámetro con Intent.
Recuperando Parámetros enviados.
Bundle bun=getIntent().getExtras();
String nombre=bun.getString("nombre");
Cuadro N 0X: Forma de recuperar parámetros enviados.
Forma Simple de pasar de una vista a otra sin parámetros de envío:
startActivity(new Intent(this, RegistroDatos.class));
4. PERSISTENCIA DE DATOS – ANDROID SQLite
4.1. Introducción a SQLite
Tipo de datos : al crear tablas en Base de Datos Equivalente SQLite Regla utilizada para
determinar la afinidad
INT
INTEGER 1
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
CHARACTER(20)
TEXT 2
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
BLOB NONE 3
no datatype specified
REAL
REAL 4 DOUBLE
DOUBLE PRECISION
FLOAT
NUMERIC
NUMERIC 5
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME
4.2. SQLiteOpenHelper
SQLiteOpenHelper es la librería que se usará para generar nuestra base de datos para SQLite.
4.3. Mantenimiento CRUD con SQLite
Manipular Datos:
4.4. Ejemplo de Aplicación
Control de Registro de Gastos Personales en Multi Idiomas:
Modelo de DB Simple:
Estructura del Proyecto:
Aquí va toda la
lógica de negocio,
dentro de archivos
.java
En esta carpeta debe
ir Archivos externos a
utilizar (Ejem: Base
de datos y otros)
En esta carpeta se
colocan las librerías
externas a utilizar
dentro del proyecto.
En Esta carpeta se
encuentra todos los
recursos de la parte
visual o vista del
proyecto.
En estas carpetas se
encuentran todas
las imágenes según
el tamaño.
En esta carpeta se deben
diseñar los formularios o
pantallas de forma visual
o gráfica
En esta carpeta es posible
definir el menu que
tendrá nuestras vistas.
En esta parte se trabajará con variables
generales para una aplicación con diferentes
idiomas.
El AndroidManifest.xml: es el archivo
principal de configuración de todo el
proyecto.
Archivos Que están dentro Values:
Archivo: strings.xml
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation"> <string name="app_name">CheckItsae</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="var_nombre">Yo</string> <string name="var_saldo">Hoy S/. 15.60</string> <string name="help">Aplicacion de control de presupuesto. Primero debe Agregar entrada a Caja Chica. Ud. Puede Agregar y ver su reporte de ingresos y egresos. </string> <string name="copy" >Copyright (C.) 2014 - www.itsae.edu.ec</string> <string name="menu_add">Agregar</string> <string name="menu_report">Reportar</string> <string name="menu_conf">Conf.</string> <string name="menu_salir">Salir.</string> <string name="menu_cancelar">Cancelar</string> <string name="titulo_add">Registrar Movimiento</string> <string name="form_Lb1">Motivo:</string> <string name="form_Lb2">Tipo:</string> <string name="form_Lb3">Cuenta:</string> <string name="form_Lb4">Monto:</string> </resources>
Para trabajar con varios Idiomas:
Se debe definir los idiomas que soportará nuestra aplicación de esta manera:
Dentro de cada values, según cada idioma deben existir los tres archivos que se muestran en la figura.
Para el caso de values-en:
Archivo strings.xml:
<?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingTranslation"> <string name="app_name">CheckItsae</string> <string name="hello_world">Hello world!</string> <string name="action_settings">Settings</string> <string name="var_nombre">I</string> <string name="var_saldo">Today S/. 15.60</string> <string name="help">Control application of budget. First you must add entrance to Petty Cash. Ud. You can add and seeing his earnings report and expenditures. </string> <string name="copy" >Copyright (C.) 2014 - www.itsae.edu.ec</string> <string name="menu_add">Add</string> <string name="menu_report">Report</string> <string name="menu_conf">Conf.</string> <string name="menu_salir">Exit.</string> <string name="menu_cancelar">Canceling</string> <string name="titulo_add">Registering Movement</string> <string name="form_Lb1">Motive:</string> <string name="form_Lb2">Type:</string> <string name="form_Lb3">Tell:</string> <string name="form_Lb4">Amount:</string> </resources>
Dentro del archivo styles.xml:
Este mismo contenido usaremos para todos los idiomas, sin embargo es posible cambiarlos por cada idioma.
<resources xmlns:android="http://schemas.android.com/apk/res/android"> <style name="AppBaseTheme" parent="Theme.AppCompat.Light"> </style> <style name="AppTheme" parent="AppBaseTheme"> </style> <!-- styles --> <style name="xtitle"> <item name="android:textColor">#FFE02E</item> <item name="android:typeface">monospace</item> <item name="android:textSize">25sp</item> </style> <style name="xstate"> <item name="android:textColor">#FFC100</item> <item name="android:textSize">15sp</item> </style> <style name="xlabel"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#FFC100</item> <item name="android:typeface">monospace</item> <item name="android:textSize">14sp</item> </style> <style name="xlabelform"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:textColor">#FFC100</item> <item name="android:typeface">monospace</item> <item name="android:textSize">13sp</item> <item name="android:textStyle">bold</item> </style> <style name="xtext"> <item name="android:textColor">#94E0FF</item> <item name="android:typeface">monospace</item> <item name="android:textSize">12sp</item> </style> <style name="xtexte">
<item name="android:typeface">monospace</item> <item name="android:textSize">12sp</item> <item name="android:background">#616161</item> </style> <style name="xcopy"> <item name="android:textColor">#505050</item> <item name="android:textSize">10sp</item> </style> <style name="xbtn"> <item name="android:textColor">#FFC100</item> <item name="android:textSize">16sp</item> </style> <style name="xbg"> <item name="android:background">#b0e8f3</item> </style> <style name="xbgIntermedio"> <item name="android:background">#616161</item> </style> <style name="xbgFondo"> <item name="android:background">#03515e</item> </style> <style name="xbtnAdd"> <item name="android:src">@drawable/icoadd</item> </style> </resources>
Definiendo los ítems del menu: (menu.xml):
<item android:id="@+id/menuAgregar" android:orderInCategory="100" android:title="@string/menu_add" app:showAsAction="never" android:icon="@drawable/add"/> <item android:id="@+id/menuReportar" android:orderInCategory="100"
android:title="@string/menu_report" app:showAsAction="never" android:icon="@drawable/report"/> <item android:id="@+id/menuConfi" android:orderInCategory="100" android:title="@string/menu_conf" app:showAsAction="never" android:icon="@drawable/conf"/> <item android:id="@+id/menuSalir" android:orderInCategory="100" android:title="@string/menu_salir" app:showAsAction="never" android:icon="@drawable/salir"/>
Contenido dentro de los archivos de Layout:
Archivo main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" style="@style/xbgFondo" android:layout_width="fill_parent" android:layout_height="fill_parent" android:focusableInTouchMode="true" android:orientation="vertical" android:scrollbars="vertical" > <TableLayout android:id="@+id/tableLayoutMenu0" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:paddingBottom="10dp" > <TableRow android:id="@+id/tableRow1" android:layout_width="fill_parent"> <TextView android:id="@+id/confName" android:text="@string/var_nombre" style="@style/xtitle" android:width="180dp"/> <TextView android:id="@+id/confState" android:text="@string/var_saldo" style="@style/xstate"/>
</TableRow> </TableLayout> <TableLayout android:id="@+id/tableLayoutMenu1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="20dp"> <TableRow android:id="@+id/tableRowMenu" android:layout_width="fill_parent"> <TableLayout android:onClick="onAdd"> <TableRow android:padding="5dp" android:layout_width="fill_parent"> <ImageView android:src="@drawable/movimiento"/> <TextView android:id="@+id/btn_text_add" android:text="@string/menu_add" style="@style/xbtn"/> </TableRow> </TableLayout> <TableLayout android:onClick="onReport"> <TableRow android:padding="5dp" android:layout_width="fill_parent"> <ImageView android:src="@drawable/report"/> <TextView android:id="@+id/btn_text_report" android:text="@string/menu_report" style="@style/xbtn"/> </TableRow> </TableLayout> <TableLayout android:onClick="onConf"> <TableRow android:padding="5dp" android:layout_width="fill_parent"> <ImageView android:src="@drawable/conf"/> <TextView android:id="@+id/btn_text_conf" android:text="@string/menu_conf" style="@style/xbtn"/> </TableRow> </TableLayout> </TableRow> </TableLayout> <TableLayout android:id="@+id/tableLayoutMenu2" android:layout_width="wrap_content" android:layout_height="wrap_content"> <Button android:layout_marginLeft="50dp" android:background="@drawable/salir" android:onClick="onFinish" android:text="@string/menu_salir"
android:textStyle="bold" android:width="0dp" /> </TableLayout> <TableLayout style="@style/xbgFondo" android:layout_width="fill_parent" android:layout_height="wrap_content" android:padding="10dp" > <TableRow android:layout_width="fill_parent" android:layout_height="wrap_content"> <TextView android:text="@string/help" android:width="250dp" android:layout_width="fill_parent" style="@style/xtext"/> </TableRow> </TableLayout> <TableLayout style="@style/xbg" android:layout_width="fill_parent" android:layout_height="fill_parent" android:onClick="onConf" android:padding="10dp" > <TableRow android:layout_width="fill_parent"> <TextView android:text="@string/app_name"/> </TableRow> <TableRow android:padding="10dp" android:layout_width="fill_parent" > <ImageView android:src="@drawable/logo6"/> <ImageView android:src="@drawable/logoupeu2"/> </TableRow> <TableRow android:layout_width="fill_parent"> <TextView android:text=""/> <TextView android:text="@string/copy" style="@style/xcopy"/> </TableRow> </TableLayout> </LinearLayout>
Archivo formulariocaja.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:focusableInTouchMode="true" style="@style/xbgFondo" android:orientation="vertical"> <TableLayout android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableRow android:id="@+id/tableRow1" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/xlabelform" android:text="@string/form_Lb1" /> <EditText android:id="@+id/formEtex1" style="@style/xtexte" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:height="30dp" > <requestFocus /> </EditText> </LinearLayout> </TableRow> <TableRow
android:id="@+id/tableRow2" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/xlabelform" android:text="@string/form_Lb2" /> <RadioGroup android:id="@+id/radTipoForm" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" > <RadioButton android:id="@+id/radTipo1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:checked="true" android:text="Ingreso" /> <RadioButton android:id="@+id/radTipo2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Egreso" /> </RadioGroup> </LinearLayout> </TableRow> <TableRow android:id="@+id/tableRow3" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal" > <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/xlabelform" android:text="@string/form_Lb3" /> <Spinner android:id="@+id/selCuentaForm" style="@style/xlabelform" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" /> </LinearLayout> </TableRow> <TableRow android:id="@+id/tableRow4" android:layout_width="fill_parent" android:layout_height="wrap_content" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <TextView android:id="@+id/textView4" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/xlabelform" android:text="@string/form_Lb4" /> <EditText android:id="@+id/formEtex2" style="@style/xtexte" android:layout_width="match_parent" android:layout_height="31dp" android:height="30dp" android:inputType="numberDecimal" > </EditText> </LinearLayout> </TableRow>
<TableRow android:id="@+id/tableRow5" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_gravity="center" > <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnform1" style="@style/xbtnAdd" android:layout_width="154dp" android:layout_height="wrap_content" android:background="@android:drawable/btn_default_small" android:onClick="onAgregar" android:text="@string/menu_add" /> <Button android:id="@+id/btnform2" android:layout_width="154dp" android:layout_height="wrap_content" android:background="@android:drawable/btn_default_small" android:text="@string/menu_cancelar" android:onClick="onRegresar"/> </LinearLayout> </TableRow> </TableLayout> </LinearLayout>
Archivo reportecaja.xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TableLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_margin="5dp"> <TableRow android:layout_width="fill_parent"> <TextView android:id="@+id/cajaReportTitle" android:text="Reporte..." style="@style/xtitle"/> </TableRow> <TableRow android:layout_width="fill_parent"> <RadioGroup android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:id="@+id/RadioGroupReporteTipo"> <RadioButton android:checked="true" android:onClick="onClickRB" android:id="@+id/RBOptionReportAll" android:text="Simple"/> <RadioButton android:checked="false" android:onClick="onClickRB" android:id="@+id/RBOptionReportOrder" android:text="Agrupado"/> </RadioGroup> </TableRow> </TableLayout> <TableLayout android:id="@+id/tableLayoutCajaReport" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="2dp"> </TableLayout> </LinearLayout>
Contenido dentro de los archivos drawable:
Contenido dentro de los archivos src: Generación y Conexión a base de datos Forma tradicional: Para poder trabajar con la base de datos SQLite se debe hacer el uso de la clase SQLiteOpenHelper, que ya viene dentro de las librerías de android, además resaltar que la mayoría de los dispositivos móviles soportan este gestor liviano de base de datos.
Archivo DBCheckItsaeSQLite.java: En este archivo se hará la generación de la base de datos. public class DBCheckItsaeSQLite extends SQLiteOpenHelper { private static final String DATABASE_NAME="dbcheckitsae.db"; public DBCheckItsaeSQLite(Context context) { super(context, DATABASE_NAME, null, 1); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub db.execSQL("CREATE TABLE configuracion (_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, nombre VARCHAR(80) NOT NULL,pmes NUMERIC NOT NULL," + " pdia NUMERIC NOT NULL, simbolo VARCHAR(6) NOT NULL); "); db.execSQL("insert into configuracion values(1,'David Mamani Pari', 80,26,'S/.');"); db.execSQL("CREATE TABLE caja (_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,fecha datetime NOT NULL,detalle VARCHAR(60) NOT NULL, " + "tipo VARCHAR(6) NOT NULL,importe NUMERIC NOT NULL,idCuenta INTEGER NOT NULL); "); db.execSQL("CREATE TABLE cuenta (_id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,nombre VARCHAR(30) NOT NULL,codigo VARCHAR(12) NOT NULL); "); db.execSQL("insert into cuenta values(1, 'Alimentacion','A001');"); db.execSQL("insert into cuenta values(2, 'Pasajes','P002');"); db.execSQL("insert into cuenta values(3, 'Otros','O003');"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.v("tareas", "DB upgrade, la data se renovara!"); db.execSQL("DROP TABLE IF EXISTS configuracion;"); db.execSQL("DROP TABLE IF EXISTS cuenta;"); db.execSQL("DROP TABLE IF EXISTS caja;"); onCreate(db); } }
Conexión a base de datos Forma Personalizada: Para esta segunda forma de conexión haremos el uso de la librería SQLiteHelperDB.jar, por otro lado se debe tener listo nuestra base de datos, la misma que debe ser colocada dentro del archivo assets -> databases.
La base de datos con la que se va a
trabajar, debe ser colocada dentro
de la carpeta databases dentro de
assets.
La libreria externa o .jar debe ser
colocada dentro de la carpeta libs.
Archivo DAOdataUtils.java: public class DAOdataUtils extends SQLiteAssetHelper { Context ctx; SQLiteDatabase db; Cursor rs; String sql; private static final String DATABASE_NAME = "dbcheckitsaedmp.db"; private static final int DATABASE_VERSION = 1; public DAOdataUtils(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } }
Archivo DAOdataUtils.java de la Primara Forma: public class DAOdataUtils { Context ctx; DBCheckItsaeSQLite data; SQLiteDatabase db; Cursor rs; String sql; public DAOdataUtils(Context context) { this.ctx=context; if(isStarted()){toStart();} // TODO Auto-generated constructor stub } public Cursor getSaldoActual() { data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); String sql="select _id, nombre, pmes, pdia, simbolo from configuracion;"; rs=db.rawQuery(sql, null);
return rs; } public Cursor getListaCuentas() { data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="select _id, nombre from cuenta;"; rs=db.rawQuery(sql, null); return rs; } public Cursor listaSimpleCaja(){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="select _id, idCuenta, strftime('%d %H:%M', fecha) as fecha, detalle, tipo, (case when tipo=='Ingreso' then importe else 0 end) as ingreso, (case when tipo=='Egreso' then importe else 0 end) as egreso from caja WHERE fecha >= datetime('"+(getFecha("yyyy-MM")+"-01 00:00:00")+"') ORDER BY _id ASC;"; rs=db.rawQuery(sql, null); return rs; } public Cursor listaGrupoCaja(){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="select c._id, c.idCuenta, strftime('%d %H:%M', c.fecha) as fecha, cu.nombre, c.tipo, (case when c.tipo=='Ingreso' then c.importe else 0 end) as ingreso, (case when c.tipo=='Egreso' then c.importe else 0 end) as egreso from caja as c, cuenta cu WHERE c.idCuenta=cu._id and fecha >= datetime('"+(getFecha("yyyy-MM")+"-01 00:00:00")+"') ORDER BY c.idCuenta, c._id ASC;"; rs=db.rawQuery(sql, null); return rs; } public void toInsert(int idCuenta, String detalle, String tipo, double importe){ data=new DBCheckItsaeSQLite(ctx); db=data.getWritableDatabase(); sql="INSERT INTO caja (idCuenta, fecha, detalle, tipo,importe) VALUES("+idCuenta+", " + "datetime('"+getFecha("yyyy-MM-dd HH:mm:ss")+"'),'"+detalle+"', '"+tipo+"', "+importe+");"; db.execSQL(sql); }
public double getPresupuesto(String tipo){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="SELECT "+tipo+" FROM configuracion; "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getDouble(0); }else{ return 0; } } public String getGrupoNm(int _id){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="SELECT nombre FROM cuenta WHERE _id="+_id+"; "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getString(0); }else{ return "< Saldo Inicial >"; } } public double getSaldo(){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="select round((importeh-imported),2) as saldo from(select 'importe' as id, ifnull(sum(importe),0) as importeh from caja where tipo='Ingreso') a left join (select 'importe' as id, ifnull(sum(importe),0) as imported from caja where tipo='Egreso') b using(id)"; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getDouble(0); }else{ return 0; }
} public void toStart(){ data=new DBCheckItsaeSQLite(ctx); db=data.getWritableDatabase(); double presupuesto=getPresupuesto("pmes"); sql="INSERT INTO caja (idCuenta, fecha, detalle, tipo,importe) VALUES(3, datetime('"+getFecha("yyyy-MM-dd HH:mm:ss")+"'),'Presupuesto', 'Ingreso', "+presupuesto+");"; db.execSQL(sql); } public boolean isStarted(){ data=new DBCheckItsaeSQLite(ctx); db=data.getReadableDatabase(); sql="select count(*) from caja where idCuenta=3 "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ if(rs.getInt(0)==0){ return true; }else{ return false; } }else{ return false; } } public String getFecha(String formato){ Date d=new Date(); SimpleDateFormat fmt=new SimpleDateFormat(formato); return fmt.format(d); } }
Archivo DAOdataUtils.java de la Segunda Forma:
public class DAOdataUtils extends SQLiteAssetHelper { Context ctx; SQLiteDatabase db; Cursor rs; String sql; private static final String DATABASE_NAME = "dbcheckitsaedmp.db"; private static final int DATABASE_VERSION = 1; public DAOdataUtils(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } public Cursor getSaldoActual() { db = getReadableDatabase(); String sql="select _id, nombre, pmes, pdia, simbolo from configuracion;"; rs=db.rawQuery(sql, null); return rs; } public Cursor getListaCuentas() { db = getReadableDatabase(); sql="select _id, nombre from cuenta;"; rs=db.rawQuery(sql, null); return rs; } public Cursor listaSimpleCaja(){ db = getReadableDatabase(); sql="select _id, idCuenta, strftime('%d %H:%M', fecha) as fecha, detalle, tipo, (case when tipo=='Ingreso' then importe else 0 end) as ingreso, (case when tipo=='Egreso' then importe else 0 end) as egreso from caja WHERE fecha >= datetime('"+(getFecha("yyyy-MM")+"-01 00:00:00")+"') ORDER BY _id ASC;"; rs=db.rawQuery(sql, null); return rs; } public Cursor listaGrupoCaja(){ db = getReadableDatabase(); sql="select c._id, c.idCuenta, strftime('%d %H:%M', c.fecha) as fecha, cu.nombre, c.tipo, (case when c.tipo=='Ingreso' then c.importe else 0 end) as ingreso, (case when c.tipo=='Egreso' then c.importe else 0 end) as egreso
from caja as c, cuenta cu WHERE c.idCuenta=cu._id and fecha >= datetime('"+(getFecha("yyyy-MM")+"-01 00:00:00")+"') ORDER BY c.idCuenta, c._id ASC;"; rs=db.rawQuery(sql, null); return rs; } public void toInsert(int idCuenta, String detalle, String tipo, double importe){ db = getReadableDatabase(); sql="INSERT INTO caja (idCuenta, fecha, detalle, tipo,importe) VALUES("+idCuenta+", datetime('"+getFecha("yyyy-MM-dd HH:mm:ss")+"'),'"+detalle+"', '"+tipo+"', "+importe+");"; db.execSQL(sql); } public double getPresupuesto(String tipo){ db = getReadableDatabase(); sql="SELECT "+tipo+" FROM configuracion; "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getDouble(0); }else{ return 0; } } public String getGrupoNm(int _id){ db = getReadableDatabase(); sql="SELECT nombre FROM cuenta WHERE _id="+_id+"; "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getString(0); }else{ return "< Saldo Inicial >"; } } public double getSaldo(){ db = getReadableDatabase();
sql="select round((importeh-imported),2) as saldo from(select 'importe' as id, ifnull(sum(importe),0) as importeh from caja where tipo='Ingreso') a left join (select 'importe' as id, ifnull(sum(importe),0) as imported from caja where tipo='Egreso') b using(id)"; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ return rs.getDouble(0); }else{ return 0; } } public void toStart(){ db = getReadableDatabase(); double presupuesto=getPresupuesto("pmes"); //Haber y Debe sql="INSERT INTO caja (idCuenta, fecha, detalle, tipo,importe) VALUES(3, datetime('"+getFecha("yyyy-MM-dd HH:mm:ss")+"'),'Presupuesto', 'Ingreso', "+presupuesto+");"; db.execSQL(sql); } public boolean isStarted(){ db = getReadableDatabase(); sql="select count(*) from caja where idCuenta=3 "; rs=db.rawQuery(sql, null); if(rs.moveToNext()){ if(rs.getInt(0)==0){ return true; }else{ return false; } }else{ return false; } } public String getFecha(String formato){ Date d=new Date(); SimpleDateFormat fmt=new SimpleDateFormat(formato); return fmt.format(d); } }
Archivo FormCaja.java:
public class FormCaja extends ActionBarActivity { DAOdataUtils utils; Cursor rs; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.formulariocaja); utils=new DAOdataUtils(this); rs=utils.getListaCuentas(); List<String> cuentas=new ArrayList<String>(); while(rs.moveToNext()){ cuentas.add(rs.getString(1)); } final Spinner spinner1 = (Spinner) findViewById(R.id.selCuentaForm); ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cuentas); adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner1.setAdapter(adapter1); } public void onAgregar(View v) { utils=new DAOdataUtils(this); int cuenta=(int)((Spinner)findViewById(R.id.selCuentaForm)).getSelectedItemId()+1; String motivo=((EditText)findViewById(R.id.formEtex1)).getText().toString(); double monto=Double.parseDouble( ((EditText)findViewById(R.id.formEtex2)).getText().toString() ); RadioButton rb_in=(RadioButton)findViewById(R.id.radTipo1); RadioButton rb_out=(RadioButton)findViewById(R.id.radTipo2); if(rb_out.isChecked() == true){ //(idCuenta, fecha, detalle, tipo,importe) utils.toInsert(cuenta, motivo,"Egreso", monto); } if(rb_in.isChecked() == true){ utils.toInsert(cuenta, motivo, "Ingreso", monto); } startActivity(new Intent(this, MainActivity.class));
} public void onRegresar(View v) { startActivity(new Intent(this, MainActivity.class)); } }
Archivo ReporteCaja.java: public class ReporteCaja extends ActionBarActivity { DAOdataUtils utils; Cursor rs; View vv; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.reportecaja); onReport(vv); } public void onClickRB(View v){ onReport(v); } public void onReport(View v){ RadioButton rb_all=(RadioButton)findViewById(R.id.RBOptionReportAll); RadioButton rb_group=(RadioButton)findViewById(R.id.RBOptionReportOrder); if(rb_all.isChecked() == true){ onReportAll(v); } if(rb_group.isChecked() == true){ onReportGroup(); } } public void onReportAll(View v){ TableLayout reporte=(TableLayout)findViewById(R.id.tableLayoutCajaReport); reporte.removeAllViews(); TableRow oper; int c=0; double tt_i=0; double tt_e=0; TextView fecha; TextView motivo; TextView ingreso; TextView egreso;TextView opcion;
Button btn; utils=new DAOdataUtils(this); rs=utils.listaSimpleCaja(); OnClickListener onclik=new OnClickListener() { @Override public void onClick(View v) { Button accion= (Button)v; Log.v("Operacion", "Si se puede"+accion.getText()); //valorA+=accion.getText(); //txtResultado.setText(valorA); } }; while(rs.moveToNext()){ c++; tt_i+=rs.getDouble(5); tt_e+=rs.getDouble(6); if(c==1){ oper=new TableRow(this); fecha=new TextView(this); fecha.setText(" Fecha"); fecha.setTextSize(12); fecha.setTextColor(Color.parseColor("#505050")); fecha.setBackgroundColor(Color.parseColor("#CEEBFF")); motivo=new TextView(this); motivo.setText(" Descripcion"); motivo.setTextSize(12); motivo.setTextColor(Color.parseColor("#505050")); motivo.setWidth(100); motivo.setBackgroundColor(Color.parseColor("#CEEBFF")); ingreso=new TextView(this); ingreso.setText(" Ingreso"); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setWidth(55); ingreso.setBackgroundColor(Color.parseColor("#CEEBFF")); egreso=new TextView(this);
egreso.setText(" Egreso"); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#CEEBFF")); opcion=new TextView(this); opcion.setText(" Del"); opcion.setTextSize(12); opcion.setTextColor(Color.parseColor("#505050")); opcion.setWidth(40); opcion.setBackgroundColor(Color.parseColor("#CEEBFF")); oper.addView(fecha); oper.addView(motivo); oper.addView(ingreso); oper.addView(egreso); oper.addView(opcion); reporte.addView(oper); } oper=new TableRow(this); fecha=new TextView(this); fecha.setText(rs.getString(2)); fecha.setTextColor(Color.YELLOW); fecha.setTextSize(8); motivo=new TextView(this); motivo.setText(rs.getString(3)); motivo.setTextSize(12); motivo.setWidth(100); ingreso=new TextView(this); ingreso.setText(""+(rs.getDouble(5))); ingreso.setTextSize(12); ingreso.setWidth(50); egreso=new TextView(this); egreso.setText(""+(rs.getDouble(6))); egreso.setTextSize(12); egreso.setWidth(50); btn=new Button(this); btn.setBackgroundColor(1); btn.setText(""+rs.getDouble(0));
btn.setOnClickListener(onclik); oper.addView(fecha); oper.addView(motivo); oper.addView(ingreso); oper.addView(egreso); oper.addView(btn); reporte.addView(oper); } oper=new TableRow(this); fecha=new TextView(this); fecha.setText(""); motivo=new TextView(this); motivo.setText(" TOTALES "); motivo.setTextSize(12); ingreso=new TextView(this); ingreso.setText(""+tt_i); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setBackgroundColor(Color.parseColor("#3FFF7D")); egreso=new TextView(this); egreso.setText(""+tt_e); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#FFBCCB")); opcion=new TextView(this); opcion.setText(" "); oper.addView(fecha); oper.addView(motivo); oper.addView(ingreso); oper.addView(egreso); oper.addView(opcion); reporte.addView(oper); oper=new TableRow(this); fecha=new TextView(this); fecha.setText(""); motivo=new TextView(this); motivo.setText("");
motivo.setTextSize(12); ingreso=new TextView(this); ingreso.setText("SALDO"); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setBackgroundColor(Color.parseColor("#3FFF7D")); egreso=new TextView(this); egreso.setText(""+(tt_i-tt_e)); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#83EAFF")); opcion=new TextView(this); opcion.setText(" "); oper.addView(fecha); oper.addView(motivo); oper.addView(ingreso); oper.addView(egreso); oper.addView(opcion); reporte.addView(oper); } public void onReportGroup(){ TableLayout reporte=(TableLayout)findViewById(R.id.tableLayoutCajaReport); reporte.removeAllViews(); TableRow oper; int g=-1; double tt_i=0; double tt_e=0; TextView fecha; TextView detalle; TextView ingreso; TextView egreso; utils=new DAOdataUtils(this); rs=utils.listaGrupoCaja(); while(rs.moveToNext()){ tt_i+=rs.getDouble(5); tt_e+=rs.getDouble(6); if(g!=rs.getInt(1)){ g=rs.getInt(1); oper=new TableRow(this); fecha=new TextView(this); fecha.setText(""); fecha.setTextSize(12);
fecha.setTextColor(Color.parseColor("#505050")); fecha.setBackgroundColor(Color.parseColor("#FFE329")); detalle=new TextView(this); detalle.setText(utils.getGrupoNm(g)); detalle.setTextSize(12); detalle.setTextColor(Color.parseColor("#505050")); detalle.setWidth(100); detalle.setBackgroundColor(Color.parseColor("#FFE329")); ingreso=new TextView(this); ingreso.setText(""); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setWidth(55); ingreso.setBackgroundColor(Color.parseColor("#FFE329")); egreso=new TextView(this); egreso.setText(""); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#FFE329")); oper.addView(fecha); oper.addView(detalle); oper.addView(ingreso); oper.addView(egreso); reporte.addView(oper); //cabeceras oper=new TableRow(this); fecha=new TextView(this); fecha.setText(" Fecha"); fecha.setTextSize(12); fecha.setTextColor(Color.parseColor("#505050")); fecha.setBackgroundColor(Color.parseColor("#CEEBFF")); detalle=new TextView(this); detalle.setText(" Descripcion"); detalle.setTextSize(12); detalle.setTextColor(Color.parseColor("#505050")); detalle.setWidth(100); detalle.setBackgroundColor(Color.parseColor("#CEEBFF")); ingreso=new TextView(this); ingreso.setText(" Ingreso");
ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setWidth(55); ingreso.setBackgroundColor(Color.parseColor("#CEEBFF")); egreso=new TextView(this); egreso.setText(" Egreso"); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#CEEBFF")); oper.addView(fecha); oper.addView(detalle); oper.addView(ingreso); oper.addView(egreso); reporte.addView(oper); } oper=new TableRow(this); fecha=new TextView(this); fecha.setText(rs.getString(2)); fecha.setTextColor(Color.YELLOW); fecha.setTextSize(8); detalle=new TextView(this); detalle.setText(rs.getString(3)); detalle.setTextSize(12); detalle.setWidth(100); ingreso=new TextView(this); ingreso.setText(""+(rs.getDouble(5))); ingreso.setTextSize(12); ingreso.setWidth(50); egreso=new TextView(this); egreso.setText(""+(rs.getDouble(6))); egreso.setTextSize(12); egreso.setWidth(50); oper.addView(fecha); oper.addView(detalle); oper.addView(ingreso); oper.addView(egreso); reporte.addView(oper); } oper=new TableRow(this);
fecha=new TextView(this); fecha.setText(""); detalle=new TextView(this); detalle.setText(" TOTALES "); detalle.setTextSize(12); ingreso=new TextView(this); ingreso.setText(""+tt_i); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setBackgroundColor(Color.parseColor("#3FFF7D")); egreso=new TextView(this); egreso.setText(""+tt_e); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#FFBCCB")); oper.addView(fecha); oper.addView(detalle); oper.addView(ingreso); oper.addView(egreso); reporte.addView(oper); oper=new TableRow(this); fecha=new TextView(this); fecha.setText(""); detalle=new TextView(this); detalle.setText(""); detalle.setTextSize(12); ingreso=new TextView(this); ingreso.setText(" SALDO: "); ingreso.setTextSize(12); ingreso.setTextColor(Color.parseColor("#505050")); ingreso.setBackgroundColor(Color.parseColor("#3FFF7D")); egreso=new TextView(this); egreso.setText(""+(tt_i-tt_e)); egreso.setTextSize(12); egreso.setTextColor(Color.parseColor("#505050")); egreso.setWidth(55); egreso.setBackgroundColor(Color.parseColor("#FFBCCB")); oper.addView(fecha);
oper.addView(detalle); oper.addView(ingreso); oper.addView(egreso); reporte.addView(oper); } }
Archivo AndroidManifest.xml: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ec.edu.itsaecheckitsae" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" /> <application android:allowBackup="true" android:icon="@drawable/logo6" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity android:name="ec.edu.itsae.checkitsae.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name="ec.edu.itsae.checkitsae.FormCaja" android:label="@string/app_name"></activity> <activity android:name="ec.edu.itsae.checkitsae.FormConfiguracion" android:label="@string/app_name"></activity> <activity android:name="ec.edu.itsae.checkitsae.ReporteCaja" android:label="@string/app_name"></activity> </application> </manifest>
Cada Clase que tiene una
implementación de Activity,
debe ser declarada en el
archivo AndroidManifest.xml
RESULTADO DE LA APLICACIÓN:
Imagen N 0X: Aplicación en Español. Imagen N 0X: Aplicación en Ingles.
5. SERVICIOS WEB EN ANDROID
5.1. Introducción a Web Service
5.2. JSON
5.3. Ejemplo de Aplicación