SlideShare una empresa de Scribd logo
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

Más contenido relacionado

DOCX
Android de la A a la Z - Unidad 6
PDF
Interfaces increibles en Android
DOCX
Manual de android parte 1
PDF
Controles y Objetos Android Studio (Actualizada 2016)
PDF
Entornos-de-Desarrollo-Eclipse-y-Android-SDK
PDF
Instalacion-y-Configuracion-de-Android-Studio-con-Genymotion
PDF
Entorno-de-Desarrollo-Android-Studio
PPTX
Versión inicial presentación Android Studio y Gradle. .
Android de la A a la Z - Unidad 6
Interfaces increibles en Android
Manual de android parte 1
Controles y Objetos Android Studio (Actualizada 2016)
Entornos-de-Desarrollo-Eclipse-y-Android-SDK
Instalacion-y-Configuracion-de-Android-Studio-con-Genymotion
Entorno-de-Desarrollo-Android-Studio
Versión inicial presentación Android Studio y Gradle. .

La actualidad más candente (14)

PDF
02 5 o8a-10231485-2-7t
PDF
Manual de android
DOCX
Android de la A a la Z - Unidad 3
PDF
Generalidades-de-Android-Estudio
PDF
Tutorial 3
DOCX
PDF
Introducción a Android
PDF
Integración sistemasembebidosaplicacionesmóviles
PDF
Instalacion y configuracion de Android Studio
DOCX
De los temas de android (introduccion-10)
PPTX
Proyecto en Android Studio (MoviCuenca)
DOCX
Adelanto de los temas de android (introduccion-10)
PDF
App en Android Studio
02 5 o8a-10231485-2-7t
Manual de android
Android de la A a la Z - Unidad 3
Generalidades-de-Android-Estudio
Tutorial 3
Introducción a Android
Integración sistemasembebidosaplicacionesmóviles
Instalacion y configuracion de Android Studio
De los temas de android (introduccion-10)
Proyecto en Android Studio (MoviCuenca)
Adelanto de los temas de android (introduccion-10)
App en Android Studio
Publicidad

Destacado (20)

PPTX
Presentación1
PPT
Racionalnye uravneniya
PPTX
final presentation.B
DOCX
My Resume copy 2
DOCX
CURRICULUM VITAE
PPT
Pryamougolnyj treugolnik reshenie_zadach
PDF
libro Percepcion cognicion y psicomotricidad
PPTX
Derecho griego
PPT
Raschet puti i_vremeni_dvizheniya
DOCX
Alzheimer's Disease (AD) final draft
PPTX
Final_Presentation
PPTX
Ave maria examinadores
PPT
Racionalnye chisla slozhenie_polozhitelnyh_i_otric
PDF
100 años de la teoria clasica
PPTX
Tarea 8
DOCX
My daily routine
PPTX
Racionalnye chisla 2
PDF
Driven: The Formula for Sustainable Success
DOCX
LETRAS CANCIONES
PPTX
End of leas cleaning Sydney by tricity cleaning
Presentación1
Racionalnye uravneniya
final presentation.B
My Resume copy 2
CURRICULUM VITAE
Pryamougolnyj treugolnik reshenie_zadach
libro Percepcion cognicion y psicomotricidad
Derecho griego
Raschet puti i_vremeni_dvizheniya
Alzheimer's Disease (AD) final draft
Final_Presentation
Ave maria examinadores
Racionalnye chisla slozhenie_polozhitelnyh_i_otric
100 años de la teoria clasica
Tarea 8
My daily routine
Racionalnye chisla 2
Driven: The Formula for Sustainable Success
LETRAS CANCIONES
End of leas cleaning Sydney by tricity cleaning
Publicidad

Similar a Manual básico de android v2.0 (20)

DOC
01 instalación del ambiente de desarrollo para android
DOCX
Componentes necesarios de android docx
PPSX
1-MD Instalacion y Primera Aplicación Móvil
DOC
Curso de intouch 10.1
PDF
Tutorial app inventor
PDF
Proyecto: Guía básica para la creación de Apps sencillas nativas sobre Android
PDF
Android
PDF
Ingeniería inversa básica en android tomo ii
PDF
Deletreando Android
PDF
Maestrosdelweb guia-android
PDF
Maestrosdelweb guia-android
PDF
Mdw guia-android
PDF
Guía Android
PDF
Mdw guia-android-1.3
PDF
Mdw guia-android-1.3
PDF
Presentacion android mistela&tweets
DOCX
Actividad 5 software de sistema y aplicaciones-lina constanza naranjo-13219...
PPTX
Taller deandroid
DOCX
Guia generalandroidstudioseccion3.docx
01 instalación del ambiente de desarrollo para android
Componentes necesarios de android docx
1-MD Instalacion y Primera Aplicación Móvil
Curso de intouch 10.1
Tutorial app inventor
Proyecto: Guía básica para la creación de Apps sencillas nativas sobre Android
Android
Ingeniería inversa básica en android tomo ii
Deletreando Android
Maestrosdelweb guia-android
Maestrosdelweb guia-android
Mdw guia-android
Guía Android
Mdw guia-android-1.3
Mdw guia-android-1.3
Presentacion android mistela&tweets
Actividad 5 software de sistema y aplicaciones-lina constanza naranjo-13219...
Taller deandroid
Guia generalandroidstudioseccion3.docx

Manual básico de android v2.0

  • 1. 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
  • 2. Í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
  • 3. 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.
  • 4. 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.
  • 5. 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”
  • 6. 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.
  • 7. 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.
  • 8. 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.
  • 9. 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.
  • 10. 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
  • 11. 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));}
  • 12. 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));
  • 13. 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
  • 14. 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:
  • 15. 4.4. Ejemplo de Aplicación Control de Registro de Gastos Personales en Multi Idiomas: Modelo de DB Simple:
  • 16. 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.
  • 17. 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.
  • 18. 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>
  • 19. 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">
  • 20. <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"
  • 21. 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"/>
  • 22. </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"
  • 23. 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>
  • 24. 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
  • 25. 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"
  • 26. 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>
  • 28. 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>
  • 29. 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.
  • 30. 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); } }
  • 31. 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.
  • 32. 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);
  • 33. 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); }
  • 34. 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; }
  • 35. } 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:
  • 36. 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
  • 37. 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();
  • 38. 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:
  • 39. 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));
  • 40. } 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;
  • 41. 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);
  • 42. 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));
  • 43. 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("");
  • 44. 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);
  • 45. 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");
  • 46. 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);
  • 47. 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);
  • 48. 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>
  • 49. Cada Clase que tiene una implementación de Activity, debe ser declarada en el archivo AndroidManifest.xml
  • 50. RESULTADO DE LA APLICACIÓN: Imagen N 0X: Aplicación en Español. Imagen N 0X: Aplicación en Ingles.
  • 51. 5. SERVICIOS WEB EN ANDROID 5.1. Introducción a Web Service 5.2. JSON 5.3. Ejemplo de Aplicación