Вы находитесь на странице: 1из 51

UNIVERSIDAD PERUANA

UNIN
FILIAL JULIACA

Facultad de Ingeniera y
Arquitectura
E.A.P. de Ingeniera de Sistemas

Manual Bsico de Programacin en Android

Autor: Ing. David Mamani Pari

2014

Intel
Universidad Peruana Unin Filial Juliaca
01/01/2014

NDICE

1.

INTRODUCCIN .....................................................................................................................................2

2.

FUNDAMENTOS E INTERFAZ DE USUARIO ...........................................................................................2

2.1.

Plataforma de Desarrollo ..................................................................................................................2

2.2.

Arquitectura del Sistema Operativo Android ...................................................................................4

2.3.

Configuracin .....................................................................................................................................4

2.4.

Aplicacin en Android .......................................................................................................................9

3.
3.1.
4.

INTENT Y SERVICIOS ............................................................................................................................11


Intent y Servicios .............................................................................................................................11
PERSISTENCIA DE DATOS ANDROID SQLite .....................................................................................12

4.1.

Introduccin a SQLite ......................................................................................................................12

4.2.

SQLiteOpenHelper ...........................................................................................................................13

4.3.

Mantenimiento CRUD con SQLite ...................................................................................................13

4.4.

Ejemplo de Aplicacin .......................................................................................................................0

5.

SERVICIOS WEB EN ANDROID .............................................................................................................36

5.1.

Introduccin a Web Service ............................................................................................................36

5.2.

JSON .................................................................................................................................................36

5.3.

Ejemplo de Aplicacin .....................................................................................................................36

CONTENIDO
1. INTRODUCCIN
En el presente documento se presenta un pequeo manual de configuracin de herramientas y el
desarrollo de aplicaciones para dispositivos con sistema operativo android (Celulares y Tablets).
Muestra los pasos bsicos a seguir en la configuracin del IDE, generacin de APK y un ejemplo de
control de gastos personales, finalmente un ejemplo de consumo de Web Service a travs de SOAP
usando JSON.

2. FUNDAMENTOS E INTERFAZ DE USUARIO


2.1. Plataforma de Desarrollo
Eclipse
Android SDK

El IDE de desarrollo Eclipse debe estar


integrado con el plugin de android
para el Eclipse. Y deben aparecer esos
2 iconos.

Imagen N 01: IDE de Desarrollo Eclipse - Integrado con el Plugin de Android.

Se debe configurar la ruta donde se


encuentra el SDK de android.

Imagen N 02: Configuracin de Android SDK.

El SDK Android debe estar actualizado


con sus diferentes versiones o al
menos un mnimo de la versin y uno
el ms reciente a fin de probar la
compatibilidad de las aplicaciones a
desarrollar.

Imagen N 03: Actualizacin de las APIS de la versin de Android.

2.2. Arquitectura del Sistema Operativo Android

Imagen N 04: Arquitectura del Sistema Operativo Android.

2.3. Configuracin
Configurar el Emulador de Android:
Para crear y ejecutar el emulador Android pulsaremos en el botn "Android Virtual Device
Manager" - "Dentro del IDE de desarrollo Eclipse

Imagen N 05: Paso 1 para configurar el Emulador de Android.

Se iniciar la aplicacin "Android Virtual Device Manager", pulsaremos "Create" para crear un
nuevo dispositivo virtual emulado:

Imagen N 06: Paso 2 para configurar el Emulador de Android.

Configuracin 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: versin 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 automticamente.
Skin: Es la seccin donde configuramos lo referido con la pantalla. Se puede seleccionar el tipo
de pantalla automticamente o ingresar la resolucin.
Front/Back Camera: Para activar la emulacin de la cmara 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 personalizacin 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 mvil 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 ejecucin de Android.

Configuracin General de ejecucin de aplicaciones:

Imagen N 10: Ignorar Problemas de empaquetado al momento de generar el APK.


Configuracin en la Aplicacin:

Imagen N 11: Problemas al generar el APK.

Imagen 0X: Error al Momento de Generar el APK.

Imagen 12: Agregar en Resources el cdigo Sombreado.


[xmlns:tools="http://schemas.android.com/tools"
tools:ignore="MissingTranslation"].

2.4. Aplicacin en Android

Imagen 0x: Primera Aplicacin en Android

Imagen N 0X: Creando el Mtodo Sumar y dando accin 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: Mtodo Sumar en Java.

Imagen 0X: Mostrando el Resultado de la Operacin.

3. INTENT Y SERVICIOS
3.1. Intent y Servicios
Pasar parmetros 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 parmetro con Intent.
Recuperando Parmetros enviados.
Bundle bun=getIntent().getExtras();
String nombre=bun.getString("nombre");
Cuadro N 0X: Forma de recuperar parmetros enviados.
Forma Simple de pasar de una vista a otra sin parmetros de envo:
startActivity(new Intent(this, RegistroDatos.class));

4. PERSISTENCIA DE DATOS ANDROID SQLite


4.1. Introduccin a SQLite

Tipo de datos : al crear tablas en Base de Datos


INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
BLOB
no datatype specified
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME

Equivalente SQLite

Regla utilizada para


determinar la afinidad

INTEGER

TEXT

NONE

REAL

NUMERIC

4.2. SQLiteOpenHelper
SQLiteOpenHelper es la librera que se usar para generar nuestra base de datos para SQLite.

4.3. Mantenimiento CRUD con SQLite


Manipular Datos:

4.4. Ejemplo de Aplicacin


Control de Registro de Gastos Personales en Multi Idiomas:
Modelo de DB Simple:

Estructura del Proyecto:

Aqu va toda la
lgica 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 libreras
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 imgenes segn
el tamao.
En esta carpeta se deben
disear los formularios o
pantallas de forma visual
o grfica

En esta carpeta es posible


definir el menu que
tendr nuestras vistas.
En esta parte se trabajar con variables
generales para una aplicacin con diferentes
idiomas.

El AndroidManifest.xml: es el archivo
principal de configuracin de todo el
proyecto.

Archivos Que estn 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 aplicacin de esta manera:

Dentro de cada values, segn 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:

Generacin y Conexin 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 libreras de android,
adems resaltar que la mayora de los dispositivos mviles soportan este gestor liviano de base de datos.

Archivo DBCheckItsaeSQLite.java: En este archivo se har la generacin 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);
}
}

Conexin a base de datos Forma Personalizada:


Para esta segunda forma de conexin haremos el uso de la librera 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


implementacin de Activity,
debe ser declarada en el
archivo AndroidManifest.xml

RESULTADO DE LA APLICACIN:

Imagen N 0X: Aplicacin en Espaol.

Imagen N 0X: Aplicacin en Ingles.

5. SERVICIOS WEB EN ANDROID


5.1. Introduccin a Web Service
5.2. JSON
5.3. Ejemplo de Aplicacin

Вам также может понравиться